When I click the button run a function called AddWait but it adds wait text to all buttons. I tried with useRef but things got messy.
Image;
I did something similar to this with jquery ;
for (let index = 0; index <= 10; index++) {
$("#app").append(`<span>Hello ${index} </span>
===><button class=click-me>button ${index} </button>
<br /><br />`);
}
$(".click-me").on("click", function (event) {
var $this = $(this);
console.log($this.text());
$this.text($this.text() + "hi");
//(... rest of your JS code)
});
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can check react app;
So how can I change only clicked button text?
import { useState } from "react";
import "./styles.css";
export default function App() {
const [waitText, setWaitText] = useState();
const [arr,setArr] = useState([
{
waitText:""
},
{
waitText:""
},
{
waitText:""
},
{
waitText:""
},
{
waitText:""
},
{
waitText:""
},
{
waitText:""
},
{
waitText:""
},
{
waitText:""
},
{
waitText:""
},
]);
const WaitThreeSeconds = (index) => {
console.log("hi");
let temp = [...arr];
temp[index].waitText = "wait"
setArr([...temp])
// setWaitText("wait");
};
return (
<div className="App">
{arr.map((x, i) => (
<div key={i}>
<span>Hello {i} </span>
<button onClick={()=>WaitThreeSeconds(i)}>
button {i} {x.waitText}
</button>
<br />
<br />
</div>
))}
</div>
);
}
You can check the sandbox code here . I hope you find it helpful :)
What you should do is save the div with the button into a separate component and then react will change the button text just for that particular component:
import { useState } from "react";
import "./styles.css";
const CustomBtn = props => {
const { item, index } = props;
console.log(item)
const [waitText, setWaitText] = useState('');
const waitThreeSeconds = () => {
setWaitText("wait");
setTimeout(() => setWaitText(''), 3000)
};
return (
<div>
<span>Hello {index} </span>
<button onClick={waitThreeSeconds}>
button {index} {waitText}
</button>
<br />
<br />
</div>
)
}
export default function App() {
return (
<div className="App">
{[...Array(10)].map((item, index) => (
<CustomBtn item={item} key={index} index={index} />
))}
</div>
);
}