'React.ReactNode to react element
I have an object of type React.ReactNode, and I want to:
1) Check if it is of type React.ReactElement
2) If yes, then I want to create a ReactElement Object equal to the node
for part 1, I am using React.isValidElement (not sure if necessary)
for part 2, i'm not sure how to do at all
In the end, I need to be able to check if a certain class is contained within the node if it is an element if that is of help. I'm assuming I need to create the ReactElement object to do this but if not that is okay as well.
Solution 1:[1]
First, you're using TypeScript (at least it looks that way by the tags) - so, ideally, you wouldn't even need to make a runtime check on the type of the object, you can do it at compile time
interface PropTypes {
something: React.ReactElement<...>
}
const M = ({ something }: PropTypes) => {
}
Second, in order to create a ReactElement from it, you can use React.cloneElement(...)
const cElement = React.cloneElement(something, something.props, [...children])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tyler Sebastian |
