Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The functional components in react are better to use if there aren't any internal state to be tracked within the component.

But what I want is to access the children of the stateless components without having to extend React.Component using which i can use props.children. Is this possible ?

If so , how to do it ?

like image 741
Natesh bhat Avatar asked Dec 23 '18 10:12

Natesh bhat


People also ask

Can a stateless component have props?

A component can be stateless and only use the props values passed to it. These values can either contain references to a calling component's state values or references to a calling component's method. props containing a method can invoke that method from the calling component.

How do you pass children and props in a functional component?

In that case, we can use the special children prop to pass children elements into the output. When some JSX is passed within the opening and closing tags of the Component being invoked, it will appear in the final output. Note that children cannot be passed with self-closing tags.


2 Answers

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.

like image 140
Ashish Avatar answered Oct 13 '22 23:10

Ashish


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.

like image 36
John Avatar answered Oct 14 '22 00:10

John