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

Am trying out react with a simple counter. Within the console.log it works perfectly but within the user interface it doesn't update the counter

I have code in my Trick.js file as follows:

let counter = 0;
const handlesclick = () => {
counter++;console.log("counter", counter)
Trick();
};
export default function Trick() {
return (
 <div>  
 <div>  
 <button onClick={handlesclick}>Increment counter</button>  
 </div>  
 <div>  
      counter value is {counter}  
 </div>  
 </div>  
  )  
}

and it is being rendered by index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import Jsx from './Jsx'
import Tools from './Tools';
import Trick from './Trick';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
    <Jsx />
    <Tools name="Ishmo" tool="Adobe"/>
    **<Trick />**
  </React.StrictMode>
);

The counter in console works perfectly but on user interface it doesn’t.
Please help me out

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 :

try this

import { useState } from "react";


export default function Trick() {

const [counter, setCounter] = useState(0);
const handlesclick = () => {
setCounter(counter + 1);
console.log("counter", counter)
};


return (
<div>  
<div>  
<button onClick={handlesclick}>Increment counter</button>  
</div>  
<div>  
  counter value is {counter}  
</div>  
</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