Ideally you should avoid using class components in 2022, the recommended way of doing components is using function components. Your last example then would look something like this:
import{useState}from"react";// We add an util to get a random item from an arrayconstpickRandomItem=array=>array[Math.floor(Math.random()*array.length)];// The component itselfexportconstRandomNames=({names,onRandomClick})=>(<div><h1>Random Names are: {names?.join(", ")}</h1><buttononClick={onRandomClick}>Randomizer</button></div>);// We set a constant with the names to be used by the appconstdefaultNames=["Jayant","Dushyant","Nitin","Gaurav","Kartik","John","Sam",];// Finally, the app that has the state and passes it to the component:exportconstApp=()=>{const[names,setNames]=useState([]);consthandleRandomClick=()=>setNames([...names,pickRandomItem(defaultNames)]);return<RandomNamesnames={names}onRandomClick={handleRandomClick}/>;};
Cheers!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Ideally you should avoid using class components in 2022, the recommended way of doing components is using function components. Your last example then would look something like this:
Cheers!