简体   繁体   中英

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:

 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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM