I have a list where is coming 0 and 1
Now I want to toggle it if I click on 1 it will be convert to 0 and if I click on 0 it will be convert to 1.
Demo:- https://codesandbox.io/s/ternary-condition-qlqpmj?file=/src/App.js
My Code:-
import React, { useState } from "react"; import { Button } from "@mui/material"; import "./styles.css"; const data = [ { title: "title1", IsActive: 1 }, { title: "title2", IsActive: 0 }, { title: "title3", IsActive: 1 }, { title: "title4", IsActive: 1 } ]; export default function App() { const [data2, setData2] = useState(data); const [updatedToggle, setUpdatedToggle] = useState(); const deleteHandle = (title, toggle) => { console.log({ title, toggle }); if (toggle === "1") { setUpdatedToggle("0"); } else { setUpdatedToggle("1"); } console.log(updatedToggle); }; return ( <div className="App"> {data2? data2.map((val, i) => ( <div className="box" key={i}> <h2>{val.title}</h2> <Button onClick={() => deleteHandle(val.title, val.IsActive)}> Delete </Button> <Button>{val.IsActive}</Button> </div> )): ""} </div> ); }
Thanks for your efforts!
This code has some of "bad code", but it will be wokrking for you.
*Using title
as a key - not good practice.
*Using i
for finding needed object - not good practice.
For this goal you need to have unique id
import React, { useState } from "react";
import { Button } from "@mui/material";
import "./styles.css";
const data = [
{
title: "title1",
IsActive: 1
},
{
title: "title2",
IsActive: 0
},
{
title: "title3",
IsActive: 1
},
{
title: "title4",
IsActive: 1
}
];
export default function App() {
const [data2, setData2] = useState(data);
const deleteHandle = (index) => {
let { IsActive } = data2[index]
IsActive = IsActive === 0 ? 1 : 0
// Copy data
const newData2 = [...data2]
newData2[index] = { ...newData2[index], IsActive }
setData2(newData2)
};
return (
<div className="App">
{data2
? data2.map((val, i) => (
<div className="box" key={val.title}>
<h2>{val.title}</h2>
<Button onClick={() => deleteHandle(i)}>
Delete
</Button>
<Button>{val.IsActive}</Button>
</div>
))
: ""}
</div>
);
}
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.