In a react component render method that has some children components in this.props.children. How can I get the component (class) name of each child to differentiate between them?
React.Children.map(this.props.children, function(child){
// how can I get the class name of a child or some other identifier
})
The state and props in React are always in an object format. This means that the value could be accessed from the state and props via key-value pair. To access the normal state object, you can use the key name from the object.
In React we can access the child's state using Refs. we will assign a Refs for the child component in the parent component. then using Refs we can access the child's state. Creating Refs Refs are created using React.
We can access any prop from inside a component's class using the above syntax. The 'this. props' is a kind of global object which stores all of a components props. The propName, that is the names of props are keys of this object.
Warning: this will not work in production if using minification
In ES6 every function has its name stored in property function.name
so you can get Class name with
import React from 'react'
...
getNameOfChildrenClass() {
const singleChild = React.children.only(this.props.children),
childClass = child.type
return childClass.name
}
I'm using React.children
utility
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With