5

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

                                        </>
                                );
                                
                            })

                            }

2 Answers 2

4

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>;
    })}
Sign up to request clarification or add additional context in comments.

Comments

1

What I do is to define a JSON file and there I define all fields, then iterate with .map()

2 Comments

i have already defined and the name is json file is registration data.but how to have new row after three labels means when three td gets loaded.it should have new after each 3 td
@Technicalknowledge I personally use the CSS framework to do the UI stuff. For a new line, you should refactor the JSON file. Maybe divide into separate arrays and then iterate each array, or try to do something with CSS framework (with <Row> and <Col>) such as Ant Design.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.