DEV Community

Discussion on: React State Pattern | Day 8

Collapse
 
loucyx profile image
Lou Cyx • Edited

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 array
const pickRandomItem = array => array[Math.floor(Math.random() * array.length)];

// The component itself
export const RandomNames = ({ names, onRandomClick }) => (
    <div>
        <h1>Random Names are: {names?.join(", ")}</h1>
        <button onClick={onRandomClick}>Randomizer</button>
    </div>
);

// We set a constant with the names to be used by the app
const defaultNames = [
    "Jayant",
    "Dushyant",
    "Nitin",
    "Gaurav",
    "Kartik",
    "John",
    "Sam",
];

// Finally, the app that has the state and passes it to the component:
export const App = () => {
    const [names, setNames] = useState([]);

    const handleRandomClick = () =>
        setNames([...names, pickRandomItem(defaultNames)]);

    return <RandomNames names={names} onRandomClick={handleRandomClick} />;
};
Enter fullscreen mode Exit fullscreen mode

Cheers!