I'm new to React. I import data from a local json file. For each item in the map generated from the data, I return an input range slider and a button. The range has an onChange event handler and the button an onClick event handler, both of which apply changes to the map values and therefore the behavior of the text in the <p className="text">
. How do I handle the events so that the changes are applied individually to each <p>
? For instance, if I move the <input name="size"
and click the <button name="align">
for the <p>
with the text 5.0
, it only changes that one? Thanks in advance for any help.
import React, { useState, useEffect } from "react";
import axios from "axios";
import "./styles.css";
function App() {
const [kitchenItems, setkitchenItems] = useState([]);
useEffect(() => {
axios
.get("./data.json")
.then((response) => setkitchenItems(response.data.kitchen));
}, []);
const onAddTextCenter = () => {
setkitchenItems(
kitchenItems.map((item) => ({
...item,
alignment: "text-center"
}))
);
};
function onSizeChange(evt) {
const sizeValue = evt.target.value;
setkitchenItems(
kitchenItems.map((item) => ({
...item,
value: sizeValue
}))
);
}
return (
<main>
{kitchenItems.map((item, i) => (
<div key={i}>
<div className="fromData">
<input
type="range"
name="size"
min={item.min}
max={item.max}
value={item.value}
step={item.step}
onChange={onSizeChange}
></input>
<button
type="button"
name="align"
onClick={() => onAddTextCenter()}
>
Text Center
</button>
</div>
<div>
<p className={"text " + item.alignment}>{item.value}</p>
</div>
</div>
))}
</main>
);
}
export default App;
Here is the CodeSandbox: https://codesandbox.io/s/quirky-gould-0rket
In case anyone has a similar dilemma, here is a solution thanks to @Yousaf from the comments:
import React, { useState, useEffect } from "react";
import axios from "axios";
import "./styles.css";
function App() {
const [kitchenItems, setkitchenItems] = useState([]);
useEffect(() => {
axios
.get("./data.json")
.then((response) => setkitchenItems(response.data.kitchen));
}, []);
const onAddTextCenter = (index) => {
const updatedData = kitchenItems.map((item, idx) => {
if (idx === index) {
return {
...item,
alignment: "text-center"
};
}
return item;
});
setkitchenItems(updatedData);
};
function onSizeChange(index, event) {
const sizeValue = event.target.value;
const updatedData = kitchenItems.map((item, idx) => {
if (idx === index) {
return {
...item,
value: sizeValue
};
}
return item;
});
setkitchenItems(updatedData);
}
return (
<main>
{kitchenItems.map((item, i) => (
<div key={i}>
<div className="fromData">
<input
type="range"
name="size"
min={item.min}
max={item.max}
value={item.value}
step={item.step}
onChange={(event) => onSizeChange(i, event)}
></input>
<button
type="button"
name="align"
onClick={() => onAddTextCenter(i)}
>
Text Center
</button>
</div>
<div>
<p className={"text " + item.alignment}>{item.value}</p>
</div>
</div>
))}
</main>
);
}
export default App;