Add component from a function on button click

Viewed 26

I want to dynamically add component every time a button is clicked. But I can't figure it out myself, and most answers I found online are class based.

This is what I wrote: I want to pass a component and a name props every time the button is clicked.

import List from "./List";

function App() {
  let listCount = 0;

  const extraList = () => {
    listCount++;
    return(
      <List name={`list-{listCount}`} />
    );
  };

  return (
  <div>
    <button onClick={extraList}>Add List</button>
  </div>
  );
}

export default App;
1 Answers

You can use useState

function App() {
    const [listCount, setListCount] = useState(0);

    const extraList = () => {
        setListCount(listCount + 1);
    };

    return (
        <div>
            {Array.from({ length: listCount }, (_, i) => i + 1).map((i) => (
                <List name={`list-${i}`} />
            ))}
            <button onClick={extraList}>Add List</button>
        </div>
    );
}
Related