I want to design the registration form in the react js. But I want to optimize the code as much as I can. I am successful in the traditional way that by using a lot of tr and td in form. what I want to achieve by using the javascript map function and want each row to contain three labels then the next row should start. I am not able to figure it out. will you help me out. Below is my JSX code.
{RegistrationData && RegistrationData.map((item,key)=>{
let row=false
if(key===0 || key===3)
row=true
else
row=false
return(
<>
{row && <tr>
<h1>{item.label}</h1>
</tr>}
</>
);
})
}
it looks like you need to make something opposite to flatten the array, So for this, I will recommend using reduce method as map will return array exactly the same length as initial array. First of all, I will transform the initial RegistrationData array [1,2,3,4,5,6,7] into the following [[1,2,3], [4,5,6], [7]] and then we can use map function to create rows and cells, hope it will help, see the example below
{RegistrationData &&
f.reduce((acc, cur) => {
if (acc.length && acc[acc.length - 1].length < 3) {
// lastRow = acc[acc.length - 1];
acc[acc.length - 1].push(cur);
} else {
acc.push([cur]); // add new row
}
return acc;
}, []).map((row) => {
return <tr>{row.map(item => (<td>item.label</td>))}</tr>;
})}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With