352

How do I select certain bars in react.js?

This is my code:

var Progressbar = React.createClass({
    getInitialState: function () {
        return { completed: this.props.completed };
    },
    addPrecent: function (value) {
        this.props.completed += value;
        this.setState({ completed: this.props.completed });
    },

    render: function () {

        var completed = this.props.completed;
        if (completed < 0) { completed = 0 };


        return (...);
    }

I want to use this React component:

var App = React.createClass({
    getInitialState: function () {

        return { baction: 'Progress1' };
    },
    handleChange: function (e) {
        var value = e.target.value;
        console.log(value);
        this.setState({ baction: value });
    },
    handleClick10: function (e) {
        console.log('You clicked: ', this.state.baction);
        document.getElementById(this.state.baction).addPrecent(10);
    },
    render: function () {
        return (
            <div class="center">Progress Bars Demo
            <Progressbar completed={25} id="Progress1" />
                <h2 class="center"></h2>
                <Progressbar completed={50} id="Progress2" />
                <h2 class="center"></h2>
                <Progressbar completed={75} id="Progress3" />
                <h2 class="center"></h2>
                <span>
                    <select name='selectbar' id='selectbar' value={this.state.baction} onChange={this.handleChange}>
                        <option value="Progress1">#Progress1</option>
                        <option value="Progress2">#Progress2</option>
                        <option value="Progress3">#Progress3</option>
                    </select>
                    <input type="button" onClick={this.handleClick10} value="+10" />
                    <button>+25</button>
                    <button>-10</button>
                    <button>-25</button>
                </span>
            </div>
        )
    }
});

I want to execute the handleClick10 function and perform the operation for my selected progressbar. But the result I get is:

 You clicked:  Progress1
 TypeError: document.getElementById(...) is null

How do I select the certain Element in react.js?

8 Answers 8

300

You can do that by specifying the ref

EDIT: In react v16.8.0 with function component, you can define a ref with useRef. Note that when you specify a ref on a function component, you need to use React.forwardRef on it to forward the ref to the DOM element of use useImperativeHandle to to expose certain functions from within the function component

Ex:

const Child1 = React.forwardRef((props, ref) => {
    return <div ref={ref}>Child1</div> 
});

const Child2 = React.forwardRef((props, ref) => {
    const handleClick= () =>{};
    useImperativeHandle(ref,() => ({
       handleClick
    }))
    return <div>Child2</div> 
});
const App = () => {
    const child1 = useRef(null);
    const child2 = useRef(null);

    return (
        <>
           <Child1 ref={child1} />
           <Child1 ref={child1} />
        </>
    )
}

EDIT:

In React 16.3+, use React.createRef() to create your ref:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

In order to access the element, use:

const node = this.myRef.current;

DOC for using React.createRef()


EDIT

However facebook advises against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases.

From the docs:

Legacy API: String Refs

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.

A recommended way for React 16.2 and earlier is to use the callback pattern:

<Progressbar completed={25} id="Progress1" ref={(input) => {this.Progress[0] = input }}/>

<h2 class="center"></h2>

<Progressbar completed={50} id="Progress2" ref={(input) => {this.Progress[1] = input }}/>

  <h2 class="center"></h2>

<Progressbar completed={75} id="Progress3" ref={(input) => {this.Progress[2] = input }}/>

DOC for using callback


Even older versions of react defined refs using string like below

<Progressbar completed={25} id="Progress1" ref="Progress1"/>

    <h2 class="center"></h2>

    <Progressbar completed={50} id="Progress2" ref="Progress2"/>

      <h2 class="center"></h2>

    <Progressbar completed={75} id="Progress3" ref="Progress3"/>

In order to get the element just do

var object = this.refs.Progress1;

Remember to use this inside an arrow function block like:

print = () => {
  var object = this.refs.Progress1;  
}

and so on...

11
  • 5
    Facebook advises against this approach. See here facebook.github.io/react/docs/refs-and-the-dom.html
    – Dmitry
    Commented Feb 10, 2017 at 16:18
  • 4
    @dmitrymar As I can see the above page is written for v15.4.2 onwards and I guess, this was not there earlier when I wrote the answer. Anyways edited the answer with the correct approach Commented Feb 13, 2017 at 3:56
  • 2
    @MattSidor, thanks for the edit, you saved me some time :-) Commented Apr 19, 2018 at 5:32
  • Um, question what if I can't access it via the "this", like what if the component I need is an instance of another class? (i.e another child react component within the parent component) Commented May 13, 2019 at 11:53
  • @akshaykishore You would need to pass the ref down using another name say innerRef and pass it to desired component Commented May 13, 2019 at 12:26
58

For getting the element in react you need to use ref and inside the function you can use the ReactDOM.findDOMNode method.

But what I like to do more is to call the ref right inside the event

<input type="text" ref={ref => this.myTextInput = ref} />

This is some good link to help you figure out.

7
  • 2
    This is the correct way to do this. This adds a reference to the element on the object/class to that you can simply use this.myTextInput to access. Commented Feb 12, 2017 at 10:42
  • 2
    How can I do this with dynamically created element? Commented Sep 17, 2019 at 13:12
  • Calling React.findDOMNode gives me react__WEBPACK_IMPORTED_MODULE_0___default.a.findDOMNode is not a function Commented Feb 23, 2020 at 4:19
  • 3
    This doesn't work with functional components: reactjs.org/docs/refs-and-the-dom.html#accessing-refs
    – Neurion
    Commented Jul 11, 2022 at 3:56
  • 1
    @Neurion Thank you for the link. It guides us on how to do this in functional components.
    – Sapthaka
    Commented Jul 15, 2022 at 4:15
56

With newer versions of React you can use and manipulate the DOM via hooks like this:

import React, { useEffect, useRef } from "react";

const MyComponent = () => {
  const myContainer = useRef(null);
  
  useEffect(() => {
    console.log("myContainer..", myContainer.current);
  });

  return (
    <>
      <h1>Ref with react</h1>
      <div ref={myContainer}>I can use the DOM with react ref</div>
    </>
  );
};

export default MyComponent;

Whenever you want to access your DOM element just use myContainer.current

3
  • 9
    Whenever you want to access your DOM element just use myContainer.current
    – Delmo
    Commented Jan 13, 2022 at 0:08
  • When you create a ref, do you have to pass that reference down the child tree or with useContext even to be able to use that anywhere else? If so your reference needs to be a parent of the component which is utterly stupid, restricted, and encapsulated... I can't just get it from anywhere with a call to get all references. Commented Nov 2, 2022 at 10:04
  • 3
    If you're using TypeScript, change the type of useRef to useRef<HTMLDivElement | null>(null) to access the object of the referenced element.
    – Victor Eke
    Commented Sep 24, 2023 at 17:39
17

You can replace

document.getElementById(this.state.baction).addPrecent(10);

with

this.refs[this.state.baction].addPrecent(10);


  <Progressbar completed={25} ref="Progress1" id="Progress1"/>
1
  • 25
    How can I do this with dynamically created element? Commented Sep 17, 2019 at 13:12
5

Disclaimer: While the top answer is probably a better solution, as a beginner it's a lot to take in when all you want is something very simple. This is intended as a more direct answer to your original question "How can I select certain elements in React"

I think the confusion in your question is because you have React components which you are being passed the id "Progress1", "Progress2" etc. I believe this is not setting the html attribute 'id', but the React component property. e.g.

class ProgressBar extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            id: this.props.id    <--- ID set from <ProgressBar id="Progress1"/>
        }
    }        
}

As mentioned in some of the answers above you absolutely can use document.querySelector inside of your React app, but you have to be clear that it is selecting the html output of your components' render methods. So assuming your render output looks like this:

render () {
    const id = this.state.id
    return (<div id={"progress-bar-" + id}></div>)
}

Then you can elsewhere do a normal javascript querySelector call like this:

let element = document.querySelector('#progress-bar-Progress1')
4

You have to follow two different ways to do it in Class and Functional components.

  1. For class components

    <input type="text" ref={ref => this.myTextInput = ref} />
    

Look at the above code. Use "ref" attribute to refer to the relevant element. Then you will be able to refer to that element using that reference. In this example, I can use "this.myTextInput" to refer to the above input element.

  1. For functional components

    const textInput = useRef(null)
    

Use the "useRef" hook and set that variable name as the value of the "ref" attribute of the element you want to refer to (like below).

<input type="text" ref={textInput} />

An example for this on functional components.

import React, {useRef} from 'react'

function CustomTextInput(props) {
  // textInput must be declared here so the ref can refer to it
  const textInput = useRef(null);

  function handleClick() {
     textInput.current.focus();
  }

  return (
    <div>
     <input type="text" ref={textInput} />
    </div>
  );
}

Want to learn more? Here you go

-1

Since React uses JSX code to create an HTML we cannot refer dom using regulation methods like documment.querySelector or getElementById.

Instead we can use React ref system to access and manipulate Dom as shown in below example:

constructor(props){

    super(props);
    this.imageRef = React.createRef(); // create react ref
}

componentDidMount(){

    **console.log(this.imageRef)** // acessing the attributes of img tag when dom loads
}


render = (props) => {

const {urls,description} = this.props.image;
    return (

            <img
             **ref = {this.imageRef} // assign the ref of img tag here**
             src = {urls.regular} 
             alt = {description}
             />

        );

}

}

2
  • 6
    This is not true. You can add an id to the img element, grab it using document.getElementById, and in most cases, it will work fine. It may cause problems/make your code harder to debug, but react/jsx donlt make it so that you CANT use native Dom methods
    – adam tropp
    Commented Jan 22, 2020 at 13:44
  • 1
    +1 because this showcases use of ref in a very simple and concise way. However, I'd like to offer the advice that the ** indicators you added will make inexperienced users think your code is broken (because technically it is with **) and generate unnecessary downvotes, so consider removing them. Also note that saying you cannot use DOM elements is untrue - you shouldn't, but you actually can. I'd rather change that line to something like "using the DOM in React to refer to elements is difficult and bad practice, therefore we use refs [...]" Commented Nov 12, 2021 at 3:17
-4

In my case, I wasn't able to use ref because elements were somewhere between many child components and I have to access them by class and id instead of ref. So, trying with useEffect hook didn't work as it can't find the element:

useEffect(() => {
  const el1 = document.querySelector('.el1')
  const el2 = document.querySelector('.el2')
}, [])

The element is undefined because when it is mounted the children components also doesn't mounted before this parent component.

So, what I did is to use timeout:

useEffect(() => {
  const timer = setTimeout(() => {
    const el1 = document.querySelector('.el1')
    const el2 = document.querySelector('.el2')
  },500)
  return () => {
    clearTimeout(timer)
  }
}, [])

Now, it worked fine. It found the DOM and I was able to manipulate with them. Hope, this helps someone!

5
  • 8
    It seems like forcing your app (and user!) to wait 500ms before updating is a bad solution. You're obviously adding a delay for the user, and this solution is still brittle as it assumes that the other components you need to access will have been rendered within 500ms. Commented Jun 11, 2021 at 14:41
  • @HartleyBrody This will run before render hook. So, there'll be no delay. It just wait for the dom available. I had no issue with this approach at all. And I clearly said that I couldn't use the ref and thus applied this trick and posted here which would help in such cases I have faced. Commented Jun 11, 2021 at 16:27
  • 2
    "Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase). Doing so will lead to confusing bugs and inconsistencies in the UI." This is an excerpt from the [reactjs.org/docs/hooks-reference.html#useeffect](React documentation for useEffect). Don't use side effects inside the function body! Commented Aug 30, 2021 at 1:13
  • The problem with this code is that it's untestable, as well as not future proof. It will work for specific computers with specific CPU speeds and load capabilities, and not for others. The moment anyone adds new, more complex code, this can cause serious bugs that show up very infrequently and are near-impossible to find. Commented Nov 12, 2021 at 3:05
  • Have you tried getting a callback ref for the outermost element root (the root of that subtree), and in your callback you could root.querySelector() for all the children and grand-children you like?
    – Martin
    Commented Mar 27, 2022 at 8:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.