Home > database >  Can i use the document object in React?
Can i use the document object in React?

Time:06-12

For an example if we made a App component and we needed to create an element each time a button was clicked:

function App() {
  const handleClick = () => {
    // Code here
  }

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

Is it ok if i used document.createElement("div") and document.getElementById("app").append() in that case?

function App() {
  const handleClick = () => {
    let div = document.createElement("div")

    div.innerHTML = "Hi!"

    document.getElementById("app").append(div)
  }

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

CodePudding user response:

It's fine to use the document object for certain things in React code, but not in this case. That's not how you'd add an element to your #app div. Instead, you'd use state for it. When switching to an MVC/MVVM/whatever tool like React, you need to stop thinking in terms of modifying the DOM and start thinking in terms of component states.

In your case, for instance, you'd either want a boolean state member telling you whether to render that Hi! div, or perhaps an array state member of messages you might display.

Here's an example of the former:

const { useState } = React;

const App = () => {
    // The state information
    const [showHi, setShowHi] = useState(false);
    
    const handleClick = () => {
        // Set the state to true on button click
        setShowHi(true);
    };
    
    return <div>
        {/* Check the state and conditionally render */}
        {showHi && <div>Hi!</div>}
        <button onClick={handleClick}>Click here</button>
    </div>;
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

I suggest working through the tutorial on the React website for a solid introduction to React.

CodePudding user response:

Yes, you can. But the React way to do this is to keep track of this in state. You can keep count of the number of divs you want to render, and update that. State update will trigger a rerender, and your view will be updated.

Below I am using a state variable count and initializing an Array using the Array() constructor of size equal to count.

function App() {
  const [count,setCount] = 0;
  const handleClick = () => {
    setCount(count => count 1);
  }

  return (
    <div id="app">
      <button onClick={handleClick}>Click here</button>
      {Array(count).map((x) => <div>{/**YOUR DIV CONTENT **/}<div>)}
    </div>
  )
}

CodePudding user response:

You don't you document.getElementById in reactjs

All point of react is to use jsx (dynamic HTML)

What you can to it's to create an array that you append item to this array each click and use map to render the new item each time :

        function App() {
        const [items,setItems] = useState([])
          const handleClick = () => {
            // Code here
    setItems(prev => {
    let arr = []
    //change obj each time to your need.
    let obj = {label : "test" , value : "test"}
    arr.push(obj)
    setItems(arr)
    })
          }
        
          return (
            <div id="app">
              <button onClick={handleClick}>Click here</button>
        {items.map((item,index) =>{
        return <p key={index}>{item.label}</p>
        })
            </div>
          )
        }

CodePudding user response:

If you need to access the DOM element, the recommended approach is to use the useRef, useImperativeHandle, useLayoutEffect, or useid hooks, as these allow React to be aware of when you are using the DOM elements, and allows for future React updates to not break your existing behavior. In your example though, I would argue that you do not need access to the DOM element, and that you should instead can let React handle the rendering of the element via declarative JSX.

  • Related