'When I output the JavaScript map function to JSX, the value comes out strangely
This is the json array I use.
console.log(materialIngredientDetail)
[
{
content: "123",
functionalList: [
{
content: "hi",
valueUnit: "42",
},
],
},
{
content: "35",
functionalList: [
{
content: "ss",
valueUnit: "88",
},
],
},
{
content: "456",
functionalList: [
{
content: "minsu",
valueUnit: "12",
},
],
},
];
Dynamically generated {Value.value Unit}
First button text 42, second button text 88, third button text 12. When these buttons are pressed, the content value is also output.
And I also executed the onClickModifyContent function using Content.current.click() useRef.
The problem is that when a button with a valueUnit value of 42 is clicked, the content is 123, but the output is 456.
const Content = useRef(null);
const valueUnit = useRef(null);
const onClickModifyContent = (content) => {
console.log(content);
};
const onClickModifiyValueUnit = (valueUnit) => {
Content.current.click();
console.log(valueUnit);
};
return (
<>
materialIngredientDetail.map((Fields, index) => (
<>
<p>{Fields.content}</p>
<button style={{"display": "none"}} ref={Content} onClick={() => onClickModifyContent(Fields.content)}></button>
</>
{Fields.functionalList.map((Value, key) => {
return (
<>
<p>{Value.valueUnit}</p>
<button onClick={() => onClickModifiyValueUnit(Value.valueUnit)}>{Value.valueUnit}</button>
</>
)
})}
))
</>
)
I'm not sure why the content is 456 when I click the button with valueUnit 42 value.
Similarly, when a button with a valueUnit value of 88 is clicked, 35 Content should be output, but a value of 456 is output. Why the hell are you doing this?
And strangely, the valueUnit value is normally output to console.log.
Solution 1:[1]
That's because you're using single ref for all of your elements. That mean's during the iteration, each element replaces the previous element as the value of Content.current. That's why, no matter what element you click, you only get the last one.
You can use something like this instead:
ref={(el)=>el && Content.current.push(el)}
And on the click function you can pass the index as well and do this:
onClick={()=>modifyValueUnit(Value.valueUnit,index)}
const modifyValueUnit = (unit,index) => {
Content.current[index].click();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
