Reputation: 767
I'd like to create 2 react components <Father />
and <Child />
and force the developer to use Child
only inside Father
:
<Father>
<!-- should be fine -->
<Child />
</Father>
<!-- should throw an error -->
<Child />
Is there any way to do it? If so, what's the syntax I should use?
Upvotes: 3
Views: 255
Reputation: 743
You can do something out of the box like this:
<Father>
{React.cloneElement(this.props.children, {...this.props, dna: 'uniquefather'})}
</Father>
Child class
...
if (this.props.dna !== 'uniquefather') throw new Error('something');
Here, the father will be passing an unique identifier, which if not received will throw error in child class.
Upvotes: 1
Reputation: 281764
You can leverage the context API
to determine whether a child has a Father
in parent or not.
The way you can do that is for your Father component to render a ContextProvider
and your child to use the context
const FatherContext = React.createContext(null); // default value used if father not in hierarchy
const Father = ({children}) => {
// Component Logic here
return (
<FatherContext.Provider value={"Father"}>
{/* rest content */
{children}
</FatherContext.Provider>
)
}
and your Child can be like
const Child = () => {
const context = useContext(FatherContext);
if(context == null) {
console.warn("Child must be rendered inside of Father component"); // You can throw an error here too
}
return (...)
}
Now depending on which version of React you use, the implementation of Context differs but the idea remains the same
Upvotes: 2