score:49

Accepted answer

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.

score:-2

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!

score:-2

the equivalent of document.getelementbyid() in react is document.queryselector().

score:-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}
             />

        );

}

}

score:3

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')

score:16

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"/>

score:28

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

score:275

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...


Related Query

More Query from same tag