Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

children prop in React component

i am learning react at the moment. this is the link with the code - http://redux.js.org/docs/basics/ExampleTodoList.html

I am having a bit of difficulty understanding what's going on in this part of the code

const Link = ({ active, children, onClick }) => {
  if (active) {
    return <span>{children}</span>
  }

  return (
    <a
      href="#"
      onClick={e => {
        e.preventDefault()
        onClick()
      }}
    >
      {children}
    </a>
  )
}

Link.propTypes = {
  active: PropTypes.bool.isRequired,
  children: PropTypes.node.isRequired,
  onClick: PropTypes.func.isRequired
}

I am having the most difficulty understand this snippet

return (
        <a
          href="#"
          onClick={e => {
            e.preventDefault()
            onClick()
          }}
        >
          {children}
        </a>
      )
    }

What does {children} mean here? What does it do?

and what does this do?

children: PropTypes.node.isRequired,

what is meant by node in the above line?

like image 846
faraz Avatar asked Jun 24 '17 08:06

faraz


1 Answers

When you use a Custom component, like

<MyComponent>Hello World</MyComponent>

Whatever you write between the tags (in above case Hello World) is passed to the component as a children prop.

So when write your component like

const Link = ({ active, children, onClick }) => {

You are destructuring the props and getting only active, children and onClick from the props passed to the component

Consider for example, you call the Link component like

<Link active="true" onClick={someFunc} style={{color: 'orange'}}>Hello</Link>

Then amongst all the props i.e active, onClick, style, children, you will only be accessing active, onClick,children in the component.

For your second question:

and what does this do?

children: PropTypes.node.isRequired,

So here PropTypes is a way of performing a typeCheck on the props that are passed to the component. It is being imported from the react-proptypes package.

So

children: PropTypes.node.isRequired

makes the prop children to be required. So if your render your component like

<Link />

It will not pass the type check and hence you need to do

<Link>Text</Link>
like image 152
Shubham Khatri Avatar answered Sep 27 '22 20:09

Shubham Khatri