Created
March 3, 2022 09:04
-
-
Save valtism/b65932c8256465c8fc71d59569f8d815 to your computer and use it in GitHub Desktop.
React children example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The bottom component we need to pass `value` to | |
function NestedComponent({ value }) { | |
return <div>The value is: {value}</div>; | |
} | |
// Example with prop drilling | |
function Example1() { | |
const [value, setValue] = useState(""); | |
return <MiddleComponent1 value={value} />; | |
} | |
// These components drill the `value` prop, even though it's not used | |
function MiddleComponent1({ value }) { | |
return ( | |
<div> | |
<MiddleComponent2 value={value} /> | |
</div> | |
); | |
} | |
function MiddleComponent2({ value }) { | |
return ( | |
<div> | |
<NestedComponent value={value} /> | |
</div> | |
); | |
} | |
// In this example, `value` is only passed to the component | |
// that needs it, without prop drilling or context | |
function Example2() { | |
const [value, setValue] = useState(""); | |
return ( | |
<ChildrenComponent1> | |
<ChildrenComponent2> | |
<NestedComponent value={value} /> | |
</ChildrenComponent2> | |
</ChildrenComponent1> | |
); | |
} | |
// These components don't need to know about the `value` prop | |
function ChildrenComponent1({ children }) { | |
return <div>{children}</div>; | |
} | |
function ChildrenComponent2({ children }) { | |
return <div>{children}</div>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment