My component in react js:
import React, { useState } from 'react';
const ComponentA = ({ children }) => {
const [state1, setState1] = useState('Hello');
const [state2, setState2] = useState('World');
// Your component logic here
return <div>{children}</div>;
};
export default ComponentA;
i need to use this method but not work but when use this not show:
const YourComponent = () => {
return (
<div>
<ComponentA>
{(state1, state2) => (
<div>
State 1: {state1}
<br />
State 2: {state2}
</div>
)}
</ComponentA>
</div>
);
};
export default YourComponent;
How to resolve that?
3
Answers
What’s the purpose of defining state1 and state2 in ComponentA, if you are not using them in that component?
The most commonly found is the parent component passsing props to the children components since React JS shares data typically in a unidirectional. Please read this article for more insight into the data flow in React JS.
The work around as shown here would be to create a callback function and pass it to the child component.
Parent Component:
ComponentA:
Honestly, I have no idea why you would want to do it this way but well, the above solution works. You could use other methods such as passing props from the parent component or simply creating a context too.
You simply call the
children
prop:And then you can do exactly as you did:
It’s a common pattern known as function-as-a-child or maybe better known as a render prop (in this case the
prop
ischildren
)