Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the class name of a React object in this.props.children

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
})
like image 907
Codewithcheese Avatar asked Jan 29 '15 15:01

Codewithcheese


People also ask

How do you access object props in React?

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.

How do you access child elements in React?

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.

How do we access props in a class?

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.


1 Answers

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

like image 164
Rudolf Gröhling Avatar answered Oct 23 '22 10:10

Rudolf Gröhling