Skip to content

Instantly share code, notes, and snippets.

@valtism
Created March 3, 2022 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valtism/b65932c8256465c8fc71d59569f8d815 to your computer and use it in GitHub Desktop.
Save valtism/b65932c8256465c8fc71d59569f8d815 to your computer and use it in GitHub Desktop.
React children example
// 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