score:49
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 }}/>
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...
Source: stackoverflow.com
Related Query
- How to access a DOM element in React? What is the equilvalent of document.getElementById() in React
- How to solve Warning: React does not recognize the X prop on a DOM element
- React, how to access the DOM element in my render function from the same component
- How to solve Warning: React does not recognize the `currentSlide`, ` slideCount` prop on a DOM element
- How to access the DOM element of the child component in Preact with hooks?
- How do I access a DOM element in a function where this.refs is unavailable in a React app?
- How to get the ref.current dom element when using react-select and react refs?
- What is the best way to call an external function on the DOM element rendered by a React stateless component?
- How to create a basic Tooltip in React where you don't actually wrap the anchor element in another DOM element?
- How to I access DOM element using 'this' keyword in React
- How to replace a set of html elements in place of a child element within the DOM rendered by React component within same component
- How to access more than one element of Dom in react using React.createRef()
- How to clear events listeners in react after removing an element from the DOM
- How to adjust the onClick event of react.children when child is a react component not a DOM element
- How to get content of a DOM element without being in the React context
- How to access the actual react rendered DOM in another application?
- How do I access the Context and Component state from within a DOM callback in a function React component?
- How to access the div element with a key in React JS? (react-dnd)
- how to remove a usestate element from the dom after 30 seconds in react js
- What is the best way to access redux store outside a react component?
- How to get the width of a react element
- How can I respond to the width of an auto-sized DOM element in React?
- React: How much can I manipulate the DOM React has rendered?
- React wrapper: React does not recognize the `staticContext` prop on a DOM element
- how to check the actual DOM node using react enzyme
- How to access the file system in react native?
- React router v4 - How do you access the state that is passed via Redirect?
- Material-UI React does not recognize the `underlineStyle` prop on a DOM element
- How to get the react component instance corresponding to event.target element in a click handler?
- Warning: React does not recognize the X prop on a DOM element
More Query from same tag
- Reactjs multiple if className's
- React native build error: Attempt to invoke virtual method'boolean com.facebook.react.uimanager.FabricViewStateManager.hasStateWrappper()
- React app does not display anything when deployed to heroku
- React-Router-Dom <Link> not render page
- Proxy API request using React Router
- Why is my hook variable in React not holding the state I set it to?
- Proper way to pop from a react component's array-type state attribute?
- How to get value from Material UI textfield after pressing enter?
- React unexepected token on a conditional HTML link
- Unable to convert class component to function component
- Background Image Not Displaying in React App
- How do you fetch a single item from mongodb and display it? (MERN)
- changing singleinput code to dynamically add more input fields with same features in react
- React Typescript Conversion issue rendering data
- How to communicate between sibling components in React
- Pass properties to React Component in DOM
- is it possible to animate a strikethrough with React Spring?
- Why is my react unit test import not working?
- Advanced conditional component rendering in react
- Select in ReactJS is picking up previous value after API call at onChange function?
- Type '{ data: InvitedUser[]; "": any; }' is not assignable to type 'Element'
- React Redux Advanced Search in front-end
- Redux + React-Router doesn't render
- Cannot use GraphQL queries in React - has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
- My socket io is working but when I add new data, it's not real time, ReactJS, Express, Mongoose
- material-table Make Row Editable on Click
- How to fix form that will not allow text to be entered?
- SSR with styled-components - when app.js loads site missing few styles
- React form upload auto submitting, depending on the order
- Gulp Bundle + Browserify on multiple files