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

React Component not updating text when I change it

When I click the increment button I expect the value displayed to go up but it stays the same

`

import * as React from 'react';

const MyComponent = () => {
  var count = 0;
  
  return (
    <div>
      <h1>Hello World</h1>
      <button onClick={() => count++}>{count}</button>
    </div>
  );
};

`

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 :

You’re not going to force a re render so your updated variable won’t show.

import React, {useState} from 'react';

const MyComponent = () => {
const [count, setCount] = useState(0);

  return (
    <div>
      <h1>Hello World</h1>
      <button onClick={() => setCount(count + 1)}>{count}</button>
    </div>
  );
};
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