Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want dynamically add table row in react js

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>}
                                        

                                        </>
                                );
                                
                            })

                            }
like image 355
Technical knowledge Avatar asked Apr 21 '21 18:04

Technical knowledge


1 Answers

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>;
    })}
like image 119
Dmytro Krasnikov Avatar answered Oct 08 '22 19:10

Dmytro Krasnikov