Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I get error when I use this code at React.Js?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading