Tipos de Componentes en ReactJS

Tipos de Componentes de Comportamiento

Stateful Component

class MiBoton extends React.Component {    constructor(props) {         super(props);
this.state.style = { background: 'blue', color: 'white' };
} render () { return ( <button {...this.props} style={this.state.styles} />
);
}
}

Componentes Stateless

const MiBoton = props => {
const styles = { background: 'blue', color: 'white' }

return (
<button
{...props}
style={styles}
/>
)
}

Pure Component

class MiBoton extends React.PureComponent {

const styles = { background: 'blue', color: 'white' }

render () {
return (
<button {...this.props} style={styles} />
);
}
}

Componentes de Órden Superior u HOC.

const TruncateHOC = WrappedComponent =>
class extends React.Component {
static propTypes = {
text: React.PropTypes.string.isRequired
};

truncateText(text) {
const maxLength = 25;

if (text.length > maxLength) {
return `${ text.substring(0, maxLength - 3) }...`;
} else {
return text;
}
}

// Renderizamos el componente
render() {
// Creamos una copia de los props actuales
let props = Object.assign({}, this.props);
// Modificamos el texto
props.text = this.truncateText(props.text);

// Renderizamos el componente principal
return <WrappedComponent { ...props } />;
}
};
let Description = props => <p>{ props.text }</p>

class Article extends React.Component {
render() {
return <article>{ this.props.text }</article>
}
}

// Se aplica el HOC!
Description = TruncateHOC(Description);
Article = TruncateHOC(Article);

Tipos de Componentes estructurales

Componentes Visuales

class Item extends React.Component {
render () {
return (
<li><a href='#'>{ this.props.valor }</a></li>
);
}
}

Componentes Contenedor

class ItemsContainer extends React.Component {
constructor (props) {
super(props);
this.state = {
temas: ['Vue', 'React JS', 'Angular']
};
}

render () {
const items = this.state.temas.map(t => (
<Item valor={ t } />
));
return (
<div>
<ul>{ items }</ul>
</div>
);
}
}

Conclusión

--

--

--

Full Stack Web Developer — adrianalonso.es

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adrián Alonso

Adrián Alonso

Full Stack Web Developer — adrianalonso.es

More from Medium

[Tech Blog] React lazy loading

Document Transition API — Creating a React Hook

Create dark mode structure in React projects (using Tailwind CSS, Typescript, and Custom Hook)

How to Calculate Values Based on Props or State in React