Browse Source

SImplify function-as-child example

main
Alex Krolick 7 years ago
parent
commit
3b908cdcbc
  1. 40
      content/docs/render-props.md

40
content/docs/render-props.md

@ -303,37 +303,23 @@ In cases where you cannot bind the instance method ahead of time in the construc
Although the examples above use `render`, any prop can be used to implement the render prop pattern. For example, the component below passes a function as the `children` prop: Although the examples above use `render`, any prop can be used to implement the render prop pattern. For example, the component below passes a function as the `children` prop:
```js ```js
<WithTitleAsync url="/my/api/books/123"> <WithTitle url="/my/api/movies/123">
{ ({ title }) => <h1>{title}</h1> } { ({ title }) => <h1>{ title }</h1> }
</WithTitleAsync> </WithTitle>
```
class WithTitleAsync extends React.Component {
constructor(props) {
super(props);
this.state = { title: null };
}
componentDidMount() { ```js
fetch(this.props.url) const WithTitle = (props) => {
.then( // In a real app the url prop would be used to fetch the title from an API
({ title }) => { this.setState({ title }) }, // Here we hard-code an example title
(error) => { this.setState({ error }) } const title = 'Babe: Pig in the City';
) const renderProp = props.children;
}
render () { return renderProp(title);
const renderProp = this.props.children; // ⬅️
if (this.state.error) {
return <span>Title Not Found</span>;
} else if (!this.state.title) {
return <span>Getting Title...</span>
} else {
return renderProp(this.state.title); // ⬅️
}
}
}; };
WithTitleAsync.propTypes = { WithTitle.propTypes = {
url: PropTypes.string.isRequired,
children: PropTypes.func.isRequired, children: PropTypes.func.isRequired,
}; };
``` ```

Loading…
Cancel
Save