Fragmentos:
// Example 1: Using empty tags <></>
render() {
return (
<>
<ComponentA />
<ComponentB />
<ComponentC />
</>
);
}
// Example 2: Using React.Fragment
render() {
return (
<React.Fragment>
<h1>An h1 heading</h1>
Some text here.
<h2>An h2 heading</h2>
More text here.
Even more text here.
</React.Fragment>
);
}
// Example 3: Importing the Fragment
import React, { Fragment } from 'react';
render() {
return (
<Fragment>
<h1>An h1 heading</h1>
Some text here.
<h2>An h2 heading</h2>
More text here.
Even more text here.
</Fragment>
);
}
return [
<li key="1">First item</li>,
<li key="2">Second item</li>,
<li key="3">Third item</li>
];
}
Espacios:
<div>
<span>My</span>
{' '}
name is
{' '}
<span>Carlos</span>
</div>
Spread atributes:
const attrs = {
id: 'myId',
className: 'myClass'
};
return <div {...attrs} />;
Esto nos sirve para pasar un estado como propiedades a otro componente:
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'CamperBot',
price:0
}
}
render() {
return (
<div>
<Navbar {...this.state} />
</div>
);
}
};
class Navbar extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>Hello, my name is: {this.props.name} {this.props.price} </h1>
</div>
);
}
};
Condicionales:
<div>
{isLoggedIn && <LoginButton />}
</div>
<div>
{isLoggedIn ? <LogoutButton /> : <LoginButton />}
</div>
Propiedades por defecto:
class Button extends React.Component {
render() {
return <button>{this.props.text}</button>;
}
}
Button.propTypes = {
text: React.PropTypes.string
};
Button.defaultProps = {
text: 'Click me!'
};
Tres maneras de hacer el binding de las funciones:
class Button extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log(this);
}
render() {
return <button onClick={this.handleClick} />;
}
}
class Button extends React.Component {
handleClick() {
console.log(this);
}
render() {
return <button onClick={() => this.handleClick()} />;
}
}
class Button extends React.Component {
handleClick = () => {
console.log(this);
}
render() {
return <button onClick={this.handleClick} />;
}
}
Cambiar estado:
// Incorrecto
this.setState({
counter: this.state.counter + this.props.increment,
});
// Correcto
this.setState((state, props) => ({
counter: state.counter + props.increment
}));