Home > front end >  React: Map over array and dynamically render a component in a specific div
React: Map over array and dynamically render a component in a specific div

Time:12-25

Probably I'm missing something really simple, but:

I have an array:

const [weight, setWeight] = useState([]);

And I want to map over it to dynamically render a component:

const renderWeight = () => {
    weight.map((e) => {
      <Weight />;
    });
  };

I want this to happen when I click on a submit button, and I want the components to render in a specific div. I can't find a way to do this.

Thank you!

CodePudding user response:

I thing you need to return the mapped array

const renderWeight = () => {
   return weight.map((e) => {
      <Weight />;
    });
  };

note: Make sure to assign a key to each component rendered

CodePudding user response:

You can use a show variable as toggler to show/hide the weight component like this

import React, { useState } from "react";

const App = () => {
  const [weight, setWeight] = useState([1, 2, 3]);
  const [show, setShow] = useState(false);

  return (
    <div className="container">
      <div className="weight">{show && weight.map((e) => <Weight />)}</div>
      <button onClick={() => setShow(!show)}>Click to show/hide</button>
    </div>
  );
};

export default App;

  • Related