Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I pass a variable as prop for setState in React?

I am trying to build a modular dropdown list component in react. It also acts as a filter for a search app.
I created an object for all the types of dropdowns and their respective options as shown in the code below.
I then mapped the object and was able to make the component I wanted to.

The problem now is, I have to update changes made to the state of filters. But I cant pass the variable "val". It takes val literally and adds a new object member.
How do I fix it?

import React from "react";

export const FilterOptions = (props) => {
  const types = {
    gender: ["", "Male", "Female", "Genderless", "Unknown"],
    status: ["", "Dead", "Alive", "Unknown"],
    species: ["", "Human", "Alien"],
  };

  return (
    <div className="flex flex-row">
      {Object.keys(types).map((val, index) => {
        return (
          <div className="mx-4">
            {val}
            <select
              name={val}
              key={index}
              onChange={(event) =>
                props.setFilters({ ...props.filters, val(This variable here is the problem): event.target.value })
              }
            >
              {types[val].map((type, index) => {
                return (
                  <option key={index} value={type}>
                    {type}
                  </option>
                );
              })}
            </select>
          </div>
        );
      })}
    </div>
  );
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use the square brackets:

props.setFilters({ ...props.filters, [val]: event.target.value })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading