Home > Mobile >  How to pass data from parent component to children but from children prop ( like Formik)
How to pass data from parent component to children but from children prop ( like Formik)

Time:07-21

I will try to explain what I want. Trying to make something like Formik. I want something like this:

<Parent>
{(someData)=>(
  <>
   {console.log(someData)}
  </>
)}
</Parent>

Parent component have children prop. How to pass this someData from Parent component?

Parent component is:

const Parent =({children})=>{
const value='Pass to children';

  return ({children})
}

How to pass this value through children porp?

Like on this link:https://formik.org/docs/guides/react-native

CodePudding user response:

I'm not exactly sure what you are trying to achieve but I do think I can help!

In react we can either pass props down to children components or we can use the useCallback hook function to pass data back to the parent, I'll show you what I mean.

As you can see in this parent element we can declare our properties which we would like to pass to our child. In this case we are passing a string with the variable name props. and a function with the variable name callLogger.

 const Parent = () => {

    const loggerFunction = (argument) => {
       console.log(argument)
    })

    return (
      <Child props={'hello world'} callLogger={loggerFunction}/>
   )
}

We can then use these values inside of our child component like so. In this example props holds a value of 'hello world'. When we use the useCallback hook, we pass in an argument, 'props'. Which is then passed back to parent component where it is called by the function we have passed in.

 const Child = ({props, callLogger}) => {

    const logger = useCallback((argument) => {
       callLogger(argument);
    })

    return (
      <div onClick={e => {e.preventDefault(); logger(props)}/>
   )
}

It may also be worth noting that in order to use this child component anywhere else you will still have to pass it the required properties in order for it to work. Hence why it is is safest to plan which components will require this data and find the best suited parents component to handle all of the logic of the two containers.

CodePudding user response:

I think you are talking about render props

const Parent = ({children}) =>{
   const value='Pass to children';

   return children(value)
}

you have to call children as function.

and you use it like this:

<Parent>
   {(someData)=>(
     <>
      {someData}
     </>
   )}
</Parent>

or like this:

<Parent children={(someData) => <>{someData}</>} />
  • Related