'React functional component - is it possible to pass props to { children }? [duplicate]

Workaround at the bottom of the question.

I am trying to pass props down to a child component using {children}.

The Father component:

const FatherComp = ({ children, propsToPassToChild }) => (
    <div>Dynamic component content: 
        {children}
    </div>
)

The child component:

const ChildComp = ({ childProps }) => <p>This is the dynamic content</p>

Using them like so:

<FatherComp>
    <ChildComp/> // childProps cannot be passed here since it's inside FatherComp
</FatherComp>

I want to pass to the ChildComp the props (propsToPassToChild ) from the FatherComp directly:

const FatherComp = ({ children, propsToPassToChild }) => (
    <div>Dynamic component content: 
        >>>>> {children} <<<<< *passing the props somewhere here* 
    </div>
)

Is it possible to achive what I am trying to do with react functional components directly and without state management?

Thanks!

************ My solution ***********

So after a little while in a different project I came accross the same question and I found out a solution.

const Father = ({ child }) => {
    return (
        <div>
            {child({ text: 'I am props from father' })}
        </div>
    );
};

const Child = ({ text }) => {
    return (
        <div>Hey there {text}</div>
    );
};

and render the Father component:

const App = () => <Father child={Child} />

Just pass the child in the props of the father as a function that returns a component. Altough it's not a 'direct' solution this solved the problem without wrapping the child with the father.



Solution 1:[1]

You should use render props

ref: https://reactjs.org/docs/render-props.html#gatsby-focus-wrapper

Solution 2:[2]

Yes, you need to do something like this:

<FatherComp>
    <ChildComp name="John" age="21"/>
</FatherComp>

const FatherComp = (props) => (
  <div>Dynamic component content: 
      {props.children}
  </div>
)

Accept props in the FatherComp and use {props.children} to render all the children components inside of your Father component.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wtlin1228
Solution 2