简体   繁体   中英

how to display content based on selected value react

I have a array of objects

const people = [
    {
        group: 'senior'
        name: 'Yoda'
    },
    {
        group: 'youth'
        name: 'Kitty'
    },
    {
        group: 'adult'
        name: 'Lisa'
    },
]

I stored the group in the dropdown list. If selecting all from the dropdown, all objects will display, if selecting senior from the dropdown, only the object has the senior value will display.

What's a good approach to do this in react?

There are many ways to approach when using ReactJS, it could base on the used component library or if you store your data in redux or component state.

Below is my approach when using component state with using <select> :

  1. Define the const to store the array of objects, let name it PEOPLE

  2. Define the people state with useState.

     const [people, setPeople] = useState(PEOPLE);
  3. The people value is filtered by the change event of the dropdown (), then I wrote a function for the onChange event of the dropdown and change state of the people in the component with the filtered value.

     function selectGroup(e) { const value = e.target.value; const filteredPeople = value === "all"? PEOPLE: PEOPLE.filter((p) => p.group === value); setPeople(filteredPeople); }

You can check for my demo here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM