Home > Blockchain >  How to change in setState specific value in array of objects onClick event?
How to change in setState specific value in array of objects onClick event?

Time:09-25

I want to change class active in my local state on click and change inActive to all other objects in the state.

const [jobType, setJobType] = useState([
        {
            "class": "active",
            "type": "All Jobs"
        },
        {
            "class": "inActive",
            "type": "My Jobs"
        },
        {
            "class": "inActive",
            "type": "Saved Jobs"
        },
    ])

const jobTypeClick = (event, item) =>{
        alert("I am clicked")
        console.log(item)
        setJobType(...jobType, jobType.class:"active")
    }

const jobTypes = jobType.map((data) => {
        return (
            <p className={data.class " mb-0 px-3 secondary-font fs-16"} key={data.type} onClick={event => jobTypeClick(event, data.type)}>{data.type}</p>
        )
    })

CodePudding user response:

This solution will work, but keep in mind that type should be unique

const jobTypeClick = (event, item) => {
    setJobType(jobType.map(t => {
        return { ...t, "class": (t.type === item) ? "active" : "inActive" }
    }))
}

Otherwise, you can pass the element index to the function this assures you uniqueness within an Array. Another nice feature is to pass a callback to set. The callback will receive the latest value allowing you to use this function even within async logic.

const jobTypeClick = (event, index) => {
    setJobType(current => current.map((t, ix) => ({ ...t, "class": (ix === index) ? "active" : "inActive" }));
}

CodePudding user response:

What you are doing in setJobType is Wrong setJobType(...jobType, jobType.class:"active")
To setJobType you need to pass an array with updated value

You need to loop all the jobTyes and make class "inActive" to all objects and make the one with same click index to "active"

You can use the below code I have added a third argument to read the index from click element and looping all jobTypes and make the correct one to active and other to inActive

const [jobType, setJobType] = useState([
        {
            "class": "active",
            "type": "All Jobs"
        },
        {
            "class": "inActive",
            "type": "My Jobs"
        },
        {
            "class": "inActive",
            "type": "Saved Jobs"
        },
    ])

const jobTypeClick = (event, item, i ) =>{
        alert("I am clicked")
        console.log(item)
        let prevJobType = [...jobType];
        prevJobType.map((d,index) => {...d, class: index == i ? "active" : "inActive")
        setJobType(prevJobType)
    }

const jobTypes = jobType.map((data, i) => {
        return (
            <p className={data.class " mb-0 px-3 secondary-font fs-16"} key={data.type} onClick={event => jobTypeClick(event, data.type, i)}>{data.type}</p>
        )
    })
  • Related