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?
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.