Home > Mobile >  How can i place values of mapped input element in a state array on the parent element
How can i place values of mapped input element in a state array on the parent element

Time:10-28

I have two components, the parent(name Parent) and child(name Child), on the parent, i map an array and render the child, so the child appears like 4 times(number of times the child is displayed based on the mapping), i have an input field on the Child component (which will be 1 input field for the rendered child component), i am basically trying to get the values of the input field from all the rendered Child component (4 been rendered based on the mapping) and then send it to my parent component (store it in a state on the parent component).

mock code

parent component

const Items = [1,2,3,4]

export const Parent= () => {

return (<div>
      {Items.map((Item, index) => {
            return (
              <div key={index}>
                <Child />
              </div>
            );
          })}
        </div>
)

}

child component


export const Child = () => {

const [Amount, setAmount] = useState();
return (

<input
   value={Amount}
   onChange={(e) => setAmount(e.target.value)}
   placeholder="Amount"
    />
)
}

sorry for the bad code formatting.

This is a mock of what it looks like

this should give a somewhat clear understanding or image of the issue, i basically want to get all the Amount on the 4 render children, place it in an array and send it to the Parent component (so i can call a function that uses all the amount in an array as an argument)

i tried to set the values of the Child component to a state on context (it was wrong, it kept on pushing the latest field values that was edited, i am new to react so i didnt understand some of the things that were said about state lifting

CodePudding user response:

try following method:

const Items = [1, 2, 3, 4];
export default function Parent() {
  return <Child items={Items} />;
}

export function Child(props) {

  const [childItems, setChildItems] = useState(props.items);

  const handleChange = (e, index) => {
    let temp = childItems;
    temp[index] = e.target.value;
    setChildItems(temp);
  };

  return (
    <div>
      {childItems.map((item, index) => {
        return (
          <div key={index}>
            <input
              value={item}
              onChange={(e) => handleChange(e, index)}
              placeholder="Amount"
            />
          </div>
        );
      })}
    </div>
  );
}```

CodePudding user response:

Congratulations, you've discovered the need for the Edit how-can-i-place-values-of-mapped-input-element-in-a-state-array-on-the-parent-el

  • Related