ReactJS, find elements by class name in React component

I have a React component. Some items will be inserted through children. Some of these elements will have a specific class name. How can I get a list of these DOM nodes in my external component?

<MyComponent>
  <div classname="snap"/>
  <p></p>
  <div classname="snap"/>
  <p></p>
  <div classname="snap"/>
</MyComponent>

What I want to know is how many elements with the class name binding are inserted into my component.

+7
source share
3 answers

You can use ReactDOM.findDOMNode. Although the documentation recommends using ref , let's see how this works:

findDOMNode ()

ReactDOM.findDOMNode(component)

DOM, DOM . DOM, DOM. ref DOM findDOMNode.

null false, findDOMNode null. , findDOMNode DOM, . React 16, , findDOMNode DOM, .


. FindDOMNode - , DOM. , . findDOMNode ( , DOM). , (, findDOMNode() render() , ), . findDOMNode .

ref, :

ref , , ref . , CustomTextInput , , :

class AutoFocusTextInput extends React.Component {
    componentDidMount() {
      this.textInput.focusTextInput();
    }

    render() {
      return (
        <CustomTextInput
          ref={(input) => { this.textInput = input; }} />
      );
    }
}

, , CustomTextInput :

class CustomTextInput extends React.Component {
  // ...
}
+5

, findDOMNode react-dom, :

ReactDOM.findDOMNode(<instance-of-outermost-component>).getElementsByClassName('snap') // Returns the elements

,

ReactDOM.findDOMNode(<instance-of-outermost-component>).getElementsByClassName('snap').length
+7

Yoy can also use this.props.childrento get the number of child nodes with a given class:

let snapCount = React.Children.toArray(this.props.children).filter((item) => item.props.className === 'snap').length;
+1
source

Source: https://habr.com/ru/post/1671785/


All Articles