Since React uses JSX code to create an HTML we cannot refer dom using regulation methods like documment.querySelector or getElementById. How do I select the certain Element in react.js? Then you can elsewhere do a normal javascript querySelector call like this: 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:
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;
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;
Use the current property to access the element in the useEffect hook. We used the useEffect hook because we want to make sure the ref has been set on the element and the element has been rendered to the DOM. The useEffect hook runs after the DOM elements in the component have been rendered to the DOM, so if an element with the provided id exists, it will be selected. Alternatively, you can use the document.getElementById method if you don't have access to the element and can't set a ref prop on it.
Copied!import {useRef, useEffect} from 'react';
export default function App() {
const ref = useRef(null);
useEffect(() => {
// 👇️ use document.getElementById()
const el = document.getElementById('my-element');
console.log(el);
// 👇️ (better) use a ref
const el2 = ref.current;
console.log(el2);
}, []);
return (
<div>
<h2 ref={ref} id="my-element">
Some content here
</h2>
</div>
);
}
Copied!useEffect(() => {
// 👇️ use document.getElementById()
const el = document.getElementById('my-element');
console.log(el);
// 👇️ (better) use a ref
const el2 = ref.current;
console.log(el2);
}, []);
Copied!useEffect(() => {
// 👇️ use document.getElementById()
const el = document.getElementById('my-element');
console.log(el);
}, []);
In React, we can make use of the useRef hook to access the reference to a DOM element. If you run the above code, enter your name in the text box and click on submit, you should be able to see an alert with your name. In this article, we will see how to achieve the same in React and will learn how to read the value of text input. If you have used vanilla JavaScript before, you might have used document.getElementById() almost every day. $(selector).val() in case you were using jQuery.
1n px create - react - app react - get - element - by - id
1import "./App.css"2
3function App() {4 const submitHandler = e => {5 e.preventDefault()6 }7
8 return (9 <div className="App">10 <form onSubmit={submitHandler}>11 <input name="name" />12 <input button type="submit" value="Submit" />13 </form>14 </div>15 )16}17
18export default App
1import { useRef } from "react"2import "./App.css"3
4function App() {5 const submitHandler = e => {6 e.preventDefault()7 alert("Name is " + inputRef.current.value)8 }9
10 const inputRef = useRef(null)11
12 return (13 <div className="App">14 <form onSubmit={submitHandler}>15 <input name="name" ref={inputRef} />16 <input button type="submit" value="Submit" />17 </form>18 </div>19 )20}21
22export default App
The getElementById Method The most common way to access an HTML element is to use the id of the element. In the example above the getElementById method used id="demo" to find the element. The easiest way to find an HTML element in the DOM, is by using the element id. The fastest way to get the DOM element is to use pure JavaScript and calling it by ID.checkbox input", row) , breaks down:
In this session, we'll try our hand at solving the How To Select A Dom Element In React puzzle by using the computer language. The code that is displayed below illustrates this point.
function App() {
const elementVariable = useRef(null)
useEffect(() => console.log(elementVariable), [] )
return (
<div ref={elementVariable}>
<h1></h1>
</div>
)
}
If you use React with Web Components (which is uncommon), use the class attribute instead. React will automatically append a “px” suffix to certain numeric inline style properties. If you want to use units other than “px”, specify the value as a string with the desired unit. For example: The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes. For example:
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
const divStyle = {
color: 'blue',
backgroundImage: 'url(' + imgUrl + ')',
};
function HelloWorldComponent() {
return <div style={divStyle}>Hello World!</div>;
}
const divStyle = {
WebkitTransition: 'all', // note the capital 'W' here
msTransition: 'all' // 'ms' is the only lowercase vendor prefix
};
function ComponentWithTransition() {
return <div style={divStyle}>This should work cross-browser</div>;
}
<div tabIndex={-1} /> // Just like node.tabIndex DOM API
<div className="Button" /> // Just like node.className DOM API
<input readOnly={true} /> // Just like node.readOnly DOM API
accept acceptCharset accessKey action allowFullScreen alt async autoComplete
autoFocus autoPlay capture cellPadding cellSpacing challenge charSet checked
cite classID className colSpan cols content contentEditable contextMenu controls
controlsList coords crossOrigin data dateTime
default defer dir disabled
download draggable encType form formAction formEncType formMethod formNoValidate
formTarget frameBorder headers height hidden high href hrefLang htmlFor
httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list
loop low manifest marginHeight marginWidth max maxLength media mediaGroup method
min minLength multiple muted name noValidate nonce open optimum pattern
placeholder poster preload profile radioGroup readOnly rel required reversed
role rowSpan rows sandbox scope scoped scrolling seamless selected shape size
sizes span spellCheck src srcDoc srcLang srcSet start step style summary
tabIndex target title type useMap value width wmode wrap
To render a React element, first pass the DOM element to ReactDOM.createRoot(), then pass the React element to root.render(): With our knowledge so far, the only way to update the UI is to create a new element, and pass it to root.render(). Unlike browser DOM elements, React elements are plain objects, and are cheap to create. React DOM takes care of updating the DOM to match the React elements. Even though we create an element describing the whole UI tree on every tick, only the text node whose contents have changed gets updated by React DOM.
const element = <h1>Hello, world</h1>;
<div id="root"></div>
const root = ReactDOM.createRoot(
document.getElementById('root')
);
const element = <h1>Hello, world</h1>;
root.render(element);
Another reason is that you may have multiple instances of the same React component on a page. When working with DOM elements we use document.getElementById() function that returns a DOM element by its id. In React, if we'd want to leverage the id property of elements we may end up with multiple HTML elements with the same id. This will cause the document.getElementById() function to return the first element with the specified id which will cause errors in our application. In this example, we access the DOM element in a click event handler handleClick to set a focus to an input element. We're using the this.inputRef.current to access the DOM element and call the focus() function. In the component's constructor we use React.createRef() function to create a reference object. It won't contain a link to a DOM element right away though. In the render function we pass the created inputRef reference object to the ref property of the input element. These two actions combined will supply us with a working DOM element reference.
import React from "react";
export default class MyComponent extends React.Component {
constructor(props) {
this.inputRef = React.createRef();
// this.inputRef.current is null here