How to Access a Dom Element in React? What Is the Equilvalent of Document.Getelementbyid() in React

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

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.

getElementById in React

You need to have your function in the componentDidMount lifecycle since this is the function that is called when the DOM has loaded.

Make use of refs to access the DOM element

<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData} ref = "cpDev1"/>

componentDidMount: function(){
var name = React.findDOMNode(this.refs.cpDev1).value;
this.someOtherFunction(name);
}

See this answer for more info on How to access the dom element in React

React dom , getElementByID

the statment is correct but you need to use getElementById after render use the function useeffect to do it like the bellow:

  React.useEffect(() => {

let ws = new WebSocket('wss://stream.binance.com:9443/ws/etheur@trade');
let stockPriceElement = document.getElementById('stock-prize');

ws.onmessage = (event)=>{
let stockObject = JSON.parse(event.data);
stockPriceElement.innerText = parseFloat(stockObject.p).toFixed(2);
}
return () => ws.close(); //closes connection on unmmount
}, [])

let me know if it's working

document.getElementById() equivalent in React 2020

I would not use a reference to check if a component is rendered inside of another one.
You could get what you're looking for with createContext and useContext.

(It could work like you tried it. If you'd pass the ref to the button as a prop.)

With the context: You create a TimerContext.Provider in your Timer component and in your button you can check with useContext(TimerContext) if the expected key is in the object. If it's not there then the button is not inside of your Timer.

Please have a look at the snippet below or in the following Codesandbox.

//import React, { useContext, createContext } from "react";

//import "./styles.css";

const { useContext, createContext } = React;

const ContainerContext = createContext({

isInContainer: null

});

const Container = () => {

return (

<ContainerContext.Provider value={{ isInContainer: true }}>

<p>

In container:

<Button />

</p>

</ContainerContext.Provider>

);

};

const Button = () => {

const { isInContainer } = useContext(ContainerContext);

console.log(isInContainer);

const isInside = () => {

alert(isInContainer ? "clicked inside" : "not in container");

};

return <button onClick={isInside}>Click me</button>;

};

function App() {

return (

<div className="App">

<Container />

<Button />

</div>

);

}

const rootElement = document.getElementById("root");

ReactDOM.render(

<React.StrictMode>

<App />

</React.StrictMode>,

rootElement

);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>

<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

reactjs this.refs vs document.getElementById

In general, refs is better than document.getElementById, because it is more in line with the rest of your react code.

In react, every component class can have multiple component instances.

And as @Isuru points out in comments: using id is dangerous, because react does not prevent you to have multiple forms on 1 page, and then your DOM contains multiple inputs with same ID. And that is not allowed.

Another advantage to using refs, is that by design, you can only access the refs in the context where you define it. This forces you to use props and state (and possibly stores) if you need to access info outside of this context.

And this an advantage, because there is less/ no chance of you breaking your unidirectional data flow, which would make your code less manageable.

NB: In almost all cases, refs can be avoided altogether. It is a design principle for Netflix to use no refs, ever, as explained by Steve McGuire (Senior User Interface Engineer at Netflix) in this video from reactjs conf 2016 (9:58m into the video).

In your case, this would mean putting the email-input value in state of the form, add on onChange handler, and use the state value in the submit event.

Why is document.getElementById() returning null in React although element is there in React?

You are not returning the image element in map function. Hence, it's not mounted in the dom tree and you can't access it using document.getElementById()

render() {
return (
{this.props.location.state.product.photos.map((photo) => {
{ console.log(photo._id); }
{/** return keyword is missing here **/}
return <img key={photo._id} id={photo._id} />;

})}
)
}

Can i use the document object in React?

Can you?

You can, but this goes against the idea of React in the first place and is advised against. Updating the DOM this way can cost you performance and even introduce bugs in your code.

The point of React is to handle updating the DOM in a performant way that is cross-browser compatible. In fact, behind the scenes, React is going to create the <div> element and place it in the DOM, but it is going to do so in a less costly and better-managed way by using a virtual representation of the DOM and everything in it. This is not as expensive as directly building, destroying and rebuilding elements on the page, because, for one, not everything on the page needs to be changed each time a user interaction that changes something of the page happens. React will react to parts of the page that have changed and keep parts that have not changed improving the performance on your web app. (See
Reactive Updates), This is one of the reasons the React library was built.

React keeps its own internal registry of elements it renders on the page, in the virtual DOM. It updates and tracks them all through their lifecycle on the page. Because of this, it knows which elements to replace, keep or tear down during user interaction. So creating an element by using the document object directly circumvents the creation (and registration) of a representation of the element in the virtual DOM making React unaware of the element - leaving the lifecycle handling of the element to the browser.

The React way

Because of the above, anything that has to do with the UI; including rendering, updating and destroying is best left to React.

The way to build (thanks to JSX and this is an improvement to @yanir's answer) your element is by simply writing out the element where you need it (or storing it in a variable first and using embedded JSX). The innerHTML attribute can be an embedded expression that is computed in the div element. Don't worry, this operation won't cost as much as using the document object to create elements directly. We'll just need a form of state to track how many times the user has clicked and create a plain JavaScript object then use the map() method to create as many <div>s as needed.

function App() { 
const [items, setItems] = useState([]);

const handleClick = () => {
let obj = { value: "Hi!" };
setItems([...items, obj]);
};

return (
<div id="app">
<button onClick={handleClick}>Click here</button>

{items.map((item, index) => {
return <div key={index}>{item.value}</div>;
})}
</div>
)
}

If you need to interact with the DOM directly, through the document object for example, as @Kaushik suggested, you can track the element through the use of hooks like useRef(), to get a reference to the object, useId() for unique stable Ids across server and client, useLayoutEffect() to hook into the browser after DOM updates but before it paints and so on. That being said, there are some APIs and attributes that you may need to access from the document object like events, title, URL, and several other attributes. In as much, as these do not mutate the UI, you can use these when needed, while the UI operations are left to React to handle.

How can I change the class of an element dynamically via url in React?

You can do something like that:

function CustomLink({ children, to, ...props }: LinkProps) {
let resolved = useResolvedPath(to);
let match = useMatch({ path: resolved.pathname, end: true });

return (
<div>
<Link
style={{ textDecoration: match ? "underline" : "none" }}
to={to}
{...props}
>
{children}
</Link>
{match && " (active)"}
</div>
);
}


Related Topics



Leave a reply



Submit