Home > database >  how do i update my state using a function onclick?
how do i update my state using a function onclick?

Time:05-11

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:

 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.

CodePudding user response:

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;
  • Related