Home > Back-end >  Why I get error when I use this code at React.Js?
Why I get error when I use this code at React.Js?

Time:11-07

Why do I get error when I use my output inside a function (without "return") like this in React.Js? What is this code's true counterpart in React?

function App() {

  function f() {
    document.getElementById("demo").innerHTML = "Hello"
  }

  f();

  return (
    <div>
    <p id='demo'></p>
    </div>
  )
}

export default App;

I tried with console.log() which worked. However I couldn't make it work when I did like it above.

CodePudding user response:

In a react component's rendered html, any dynamically rendered content should be done so with state. In your case, the useState() hook is what you want:

import { useState } from 'react';

function App() {
  const [helloMessage] = useState('hello');

  return (
    <div>
      <p id='demo'>{helloMessage}</p>
    </div>
  );
}

export default App;

If you wish to then update a piece of state, you can add a second variable to the useState()'s de-structured array that will then be assigned a function used to update the state when called:

import { useState } from 'react';

function App() {
  const [helloMessage, setHelloMessage] = useState('hello');

  return (
    <div>
      <input
        value={helloMessage}
        onChange={(e) => setHelloMessage(e.target.value)}
      />
      <p id='demo'>{helloMessage}</p>
    </div>
  );
}

export default App;

Hope this helps.

  • Related