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

how do i update my state using a function onclick?

I’m making a simple rock paper scissors app I have an array of ‘rock’, ‘paper’, and ‘scissors, and I’m mapping it. but the problem is that when i click the button it should update the state through the handle click function and should display user choice

here is my app component:

import { useState } from "react";

const App = () => {
  const [userChoice, setuserChoice] = useState(null);
  const choices = ["rock", "paper", "scissors"];
  const handleClick = (value) => {
    console.log('hi');
    setuserChoice(value);
  };
  return (
    <div>
      <h1>Userchoice is:</h1>
      <h1>compute choice is :</h1>
      <>
      {choices.map(choice  => <button key={choice} onClick={()=>handleClick(choice)}>{choice}</button>)}
      
      </>


    </div>
  );
};

export default App;

here is my index.js:

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

 import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

I was having trouble rendering the list using the map what worked for that was wrapping my map function in a fragment im new to reacting so I’m not sure.
what i want is when someone clicks on the rock button it should update the state and display rock as the user choice.

>Solution :

Everything is just right, you just forgot to render userChoice state.

import { useState } from 'react';

const App = () => {
const [userChoice, setuserChoice] = useState(null);
const choices = ['rock', 'paper', 'scissors'];
const handleClick = (value) => {
    console.log('hi');
    setuserChoice(value);
};
return (
    <div>
        <h1>Userchoice is: {userChoice}</h1>
        <h1>compute choice is :</h1>
        <>
            {choices.map((choice) => (
                <button key={choice} onClick={() => handleClick(choice)}>
                    {choice}
                </button>
            ))}
        </>
    </div>
);
};

export default App;
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