score:1
here's an example how you could do it.
as you can see child
became presentational component and only shows data.
rest of logic went to the parent component.
const { usestate, useeffect, fragment } = react;
const child = ({nr, user, onaddfield, onchange}) => {
return <div>
<div>{nr}</div>
{user.map(({firstname, lastname}, index) => <div key={index}>
<input onchange={({target: {name, value}}) => onchange(nr, index, name, value)} value={firstname} name="firstname" type="text"/>
<input onchange={({target: {name, value}}) => onchange(nr, index, name, value)} value={lastname} name="lastname" type="text"/>
</div>)}
<button onclick={() => onaddfield(nr)}>add field</button>
</div>
}
const app = () => {
const [items, setitems] = usestate([
{
nr: 1,
user: []
},
{
nr: 2,
user: [
{firstname: 'test1', lastname: 'test1'},
{firstname: 'test2', lastname: 'test2'}
]
}
]);
const oncountchange = ({target: {value}}) => {
setitems(items => {
const computedlist = array(number(value)).fill(0).map((pr, index) => ({
nr: index + 1,
user: []
}))
const merged = computedlist.reduce((acc, value) => {
const item = items.find(pr => pr.nr === value.nr) || value;
acc = [...acc, item];
return acc;
}, [])
return merged;
})
}
const onchildchange = (nr, index, name, value) => {
setitems(items => {
const newitems = [...items];
const item = newitems.find(pr => pr.nr === nr);
const field = item.user.find((pr, ind) => index === ind)
field[name] = value;
return newitems;
});
}
const onaddfield = (nr) => {
setitems(items => {
const newitems = [...items];
const item = newitems.find(pr => pr.nr === nr);
item.user = [...item.user, {
firstname: '',
lastname: ''
}];
return newitems;
})
}
const onclick = () => {
console.log({data: items});
}
return <div>
{items.map((pr, index) => <child {...pr} onaddfield={onaddfield} onchange={onchildchange} key={index} />)}
<input onchange={oncountchange} value={items.length} type="number"/>
<button onclick={onclick}>submit</button>
</div>
}
reactdom.render(
<app />,
document.getelementbyid('root')
);
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>
Source: stackoverflow.com
Related Query
- Save values in array of data
- how to save array object data in redux store
- React - Combine data returned two api calls and set state of an array with these values
- I want to save all Button values in array using ReactJs
- How do I create an array of unique field values in React with data from Firestore?
- Save latest string values in react state array
- How to save data in an array inside state in react js
- how to loop through data and assign values to state array in react
- How to store input values of a form in a array to print array data in table list in Reactjs
- Access form values - array of data
- Save the localStorage data in array of objects in state
- Getting initial useState list values when returning from a sub componet to save data instead of current state
- How to save data to array axios?
- Get an array after filtering the data from the given values in javascript react
- Fetched data from external api,how to loop through the array and display values
- Capture individual select drop-down values when data is nested inside an array
- axios post array data
- Finding an object in array and taking values from that to present in a select list
- React.js: loading JSON data with Fetch API and props from object array
- Most efficient way of rendering JSX elements when iterating on array of data in React
- React JS: how to properly remove an item from this.state.data where data is an array of objects
- Removing duplicate array values and then storing them [react]
- How to count number of occurrences of distinct values from an array of objects in Javascript?
- Append array of values to the current array in a state in React JS
- RxJS and React multiple clicked elements to form single data array
- update/merge array values in React Redux store correctly without duplicates
- How to loop through an array of data in React-native?
- react-table iterating over object array to print values in a column
- Checking if items within mapped array share values
- How to edit react bootstrap table and save data after editing
More Query from same tag
- How do I get the normal photo?
- How to set initial value in Select tag in React
- How to deploy React Next.JS on iis?
- Validating visible fields conditionally using React TSX React-hook-forms Yup
- How to prevent use my API which gives data for my React app
- React render nested component
- pass props with Lazy loading in react-router-dom v6
- I cant delete list from react function component
- Export image node to markdown with Lexical
- Select multiple files in react with refs
- Does material-ui useStyles really requires the entire props object?
- Generate an array in React using specific code
- typescript Object is possibly null when getting files from event
- How to get firestore instance with react-redux-firebase?
- What does the meaning of this line of codes ` skills: { ...this.state.skills, [name]: checked }`?
- Typescript - Omit props types of HoC
- Server side rendering with React-rails and Algolia
- Firebase Realtime Database validations rules not working
- React state still changing when set via localstorage
- component not re-rendering when updating the state in mobx
- Why is my function inside componentDidMount not being fired?
- constant height for carousal with items having different height
- Styling in Material UI
- Testing components using React Relay
- Protected page using react-router-dom doesn't work
- Unit test in React requires construct or call signatures
- Imgur images returning 403
- react JS render a component after a click
- React useContext Returning Undefined
- Undefined e.target.name for toggled state component