Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering children props in pure ReactJS (functional) component

React v0.14 supports pure functional components (i.e. same input equals same output). Props are passed in as function arguments.

// Using ES6 arrow functions and an implicit return:
const PureComponent = ({url}) => (
  <div>
    <a href={url}>{url}</a>
  </div>
);

// Used like this:
<PureComponent url="http://www.google.ca" />

// Renders this:
<a href="http://www.google.ca">http://www.google.ca</a>

But how do you render children of the PureComponent? In regular stateful components you access the children with this.props.children, but this obviously doesn't work here.

const PureComponent = ({url}) => (
  <div>
    <a href={url}>{children}</a> // <--- This doesn't work
  </div>
);

<PureComponent url="http://www/google.ca">Google Canada</PureComponent>

// I want to render this:
<a href="http://www.google.ca">Google Canada</a>

What should I do?

like image 592
user5670895 Avatar asked Jan 28 '16 23:01

user5670895


1 Answers

You need to add children to the destructuring assignment of the argument "props".

const PureComponent = ({url, children}) => (...)

children is just a prop passed to the component. In order to use it like you are using props.url you need to add it to that list so it can be "pulled out" of the props object.

like image 92
Rob Lynch Avatar answered Nov 15 '22 20:11

Rob Lynch