How to access props.children in a stateless functional component in react? How to access props.children in a stateless functional component in react? reactjs reactjs

How to access props.children in a stateless functional component in react?


We can use props.children in functional component. There is no need to use class based component for it.

const FunctionalComponent = props => {  return (    <div>      <div>I am inside functional component.</div>      {props.children}    </div>  );};

When you will call the functional component, you can do as follows -

const NewComponent = props => {  return (    <FunctionalComponent>      <div>this is from new component.</div>    </FunctionalComponent>  );};

Hope that answers your question.


Alternatively to the answer by Ashish, you can destructure the "children" property in the child component using:

const FunctionalComponent = ({ children }) => {  return (    <div>      <div>I am inside functional component.</div>      { children }    </div>  );};

This will allow you to pass along other props that you would like to destructure as well.

const FunctionalComponent = ({ title, content, children }) => {  return (    <div>      <h1>{ title }</h1>      <div>{ content }</div>      { children }    </div>  );};

You can still use "props.title" etc to access those other props but its less clean and doesn't define what your component accepts.