Home > Mobile >  Change the stars color onClick using reactjs
Change the stars color onClick using reactjs

Time:07-16

Today I had interview of reactjs but I wasn't able to solve the given problem. Can anyone help me with this. Create a screen with 5 stars on it. (You can use asterisk(*) key instead of stars). Initially all stars are black. When the user clicks on any star, all the stars before the clicked star should become blue, the star clicked should become red and all the stars after the clicked star should remain black. For eg: If you clicked 3rd star then 1st and 2nd star will become blue, the 3rd star will become red and the 4th and 5th star will become black

You have to code this in react. Do not use any external libraries.

CodePudding user response:

For explanations check Aymen Hammami's answer

function App() {
  const [star, setStar] = React.useState(-1)
  return (
  <React.Fragment>
     {  Array(5).fill().map((x,i)=>i).map(elem =>
     <button key={elem}
        onClick={()=>setStar(elem)} 
        style={
          star == -1 ? 
            {backgroundColor: 'black'} 
            :
            star == elem ? {backgroundColor: 'red'} :
            star <= elem ? 
              {backgroundColor: 'black'} 
              : 
              {backgroundColor: 'blue'}
     }>
        X
     </button>
        )
     }

  </React.Fragment>
  )
}

ReactDOM.render( <App/> , document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>

CodePudding user response:

According to the information you have provided I feel like this can be the answer

const stars = [
  { num: 1, symbol: "*" },
  { num: 2, symbol: "**" },
  { num: 3, symbol: "***" },
  { num: 4, symbol: "****" },
  { num: 5, symbol: "*****" }
];

const StarComponent = () => {
  const [starNumber, setStarNumber] = useState(0);

  const onClickHandler = (val) => {
    setStarNumber(val);
  };

  return (
    <>
      {stars.map((star) => (
        <div
          key={star.num} 
          onClick={() => onClickHandler(star.num)}
          style={{ color: star.num < starNumber ? "blue" : star.num === starNumber ? "red" : "black"  }}
        >
          {star.num}
          {star.symbol}
        </div>
      ))}
    </>
  );
};

export default StarComponent;

  • Related