Composition Flashcards
Composition with functional components
Some components don’t know their children ahead of time. This is especially common for components like Sidebar or Dialog that represent generic “boxes”.
We recommend that such components use the special children prop to pass children elements directly into their output:
function FancyBorder(props) { return ( <div> {props.children} </div> ); }
This lets other components pass arbitrary children to them by nesting the JSX:
function WelcomeDialog() { return (
<h1> Welcome </h1> <p> Thank you for visiting our spacecraft! </p>
);
}
Anything inside the JSX tag gets passed into the FancyBorder component as a children prop. Since FancyBorder renders {props.children} inside a <div>, the passed elements appear in the final output.</div>
Composition with class components
Composition works equally well for components defined as classes:
class SignUpDialog extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleSignUp = this.handleSignUp.bind(this); this.state = {login: ''}; }
render() {
return (
Sign Me Up! ); }
handleChange(e) {
this.setState({login: e.target.value});
}
handleSignUp() {
alert(Welcome aboard, ${this.state.login}!
);
}
}