How do I efficiently render multiple form field components in React CSS when two of them have different flex directions?

I need to find a way to dynamically iterate through multiple input components. All inputs follow the same style pattern except for 'first name' and 'last name', which should be aligned in one row with different widths.

<div style={{flexDirection: 'column'}}>
<div style={{flexDirection: 'row'}}>
<FormInput
       name="firstname"
       placeholder="First name"
       onChange={onChange}
       value={value}
       errors={errors}
       width="45%"
/>
<FormInput
       name="lastname"
       placeholder="Last name"
       onChange={onChange}
       value={value}
       errors={errors}
       width="45%"
/>
</div>
<FormInput
       name="email"
       placeholder="email"
       onChange={onChange}
       value={value}
       errors={errors}
       width="90%"
/>
...
</div>
Object.entries({firstname: 'Fist Name', lastname: 'Last Name', email: 'Email', password: 'Password', passwordConfirm: 'Confirm Password'}).map(item=> {
    return (
      <FormInput
       name={item[0]}
       placeholder={item[1]}
       onChange={onChange}
       value={value}
       errors={errors}
       width=??
      />
    )
})

Is there a way to loop through all input fields while accommodating the unique styling requirements of two of them? I appreciate any suggestions!

Answer №1

To efficiently utilize the array obtained from Object.entries, ensure you destructure it to handle the initial two entries, representing first and last names, in a distinct manner:

// Consider using `useMemo` if there's a chance of object mutation
const [firstName, lastName, ...fields] = Object.entries({firstname: 'First Name', lastname: 'Last Name', email: 'Email', password: 'Password', passwordConfirm: 'Confirm Password'});

// Constructing your template
return {
  <div style={{flexDirection: 'column'}}>
    <div style={{flexDirection: 'row'}}>
      <FormInput
            name={firstName[0]}
            placeholder={firstName[1]}
            onChange={onChange}
            value={value}
            errors={errors}
            width="45%"
      />
      <FormInput
            name={lastName[0]}
            placeholder={lastName[1]}
            onChange={onChange}
            value={value}
            errors={errors}
            width="45%"
      />
    </div>
    {fields.map(item=> (
      <FormInput
        name={item[0]}
        placeholder={item[1]}
        onChange={onChange}
        value={value}
        errors={errors}
        width="90%"
      />
    ))}
  </div>
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"I am interested in using the MongoDB database with Mongoose in a Node.js application to incorporate the

I am facing a situation where I need to validate the name and code of a company, and if either one matches an existing record in the database, it should notify that it already exists. Additionally, when receiving data with isDeleted set to true, I want to ...

Placeholder fails to appear

After implementing some jQuery validation, I wanted to display a text as a placeholder when the user skipped out of an input field without entering anything. This is the code I wrote: $('input[type="text"]').on('blur', function() { ...

How can I pass the rowData argument in React Material-Table components?

I am currently working on implementing material-table for React. My code successfully retrieves data from an API, but I need to open a Popup window that will make another API call. In order to do this, I require the value of rowData.ID_value_to_call. At t ...

Navigating between pages using React-router-dom

Just implemented a simple navigation using react-router-dom. Managed to get it working with this.props.history.push('/pathName'); But I'm not entirely sure if my understanding and approach are correct. Any advice on correcting my mistakes wo ...

Discovering the Newest Product Updates through API Integration

I have a component that displays only the most recent product fetched from an API: const about = ({products}) => { const data = products.attributes console.log(data) return ( <div> <h1>{data.Name}</h1> ...

Guide to embedding a qr code within a pdf document

I've been working on creating a PDF file generation feature where users can download the PDF with a QR code embedded in it. While I've successfully implemented the PDF generation part, I'm facing an issue with adding the QR code to the file. ...

React: Modifying state does not update useState array

The state of the array does not change when the state change method is called : const [arrayOfDocuments, setArrayOfDocuments] = useState([]); I have tried : setArrayOfDocuments(...[]); or setArrayOfDocuments([]); Where I use my method : const pushToArr ...

Switch color in Material-UI based on props

Utilizing code inspired by the Material-UI documentation on customizing the switch, you can customize the switch color to be blue: import React from 'react' import Switch from '@material-ui/core/Switch' import {withStyles} from '@ ...

Error: Unable to assign the 'schedule' property to a null value

I'm currently developing a scheduling application using React.js and have implemented a draggable scheduling feature for users to indicate their availability. Everything seems to be working smoothly, except for one pesky error message: TypeError: Cann ...

What is the best way to handle alias components in next.js when using ts-jest?

When working with TypeScript, Next.js, and Jest, I wanted to simplify my imports by using aliases in my tsconfig file instead of long relative paths like "../../..". It worked fine until I introduced Jest, which caused configuration issues. This is a snip ...

What process does npm use to identify when a package version has become vulnerable and display it in the command prompt?

As I dive into my react project, relying on various npm packages, I encountered a concerning issue. Initially, there were 1002 vulnerable packages that needed fixing or updating. After some effort, only 20 vulnerabilities remained, and they were deemed low ...

Having trouble with your website not adjusting properly when resizing the browser or viewing it on a mobile phone

My website is not adapting properly to different screen sizes, even after I have added the META tags below. Any advice would be appreciated. Thank you. HTML <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8> ...

JavaScript function to toggle the visibility of navigation with a click of a button

I'm attempting to create a functionality in my code where the Open navigation button hides when the side navigation opens upon clicking. The desired behavior is for the openNav button to be hidden when it's clicked and then shown again when close ...

When hovering over a circle in CSS with a background image to hide text, the shape becomes distorted

I am attempting to create a series of circles with background images and accompanying text displayed side by side. My goal is to have the image opacity change and the text disappear upon hovering over each circle. Additionally, I do not want underlines to ...

Styling with CSS in a React component

I am trying to display a row of buttons instead of columns on my webpage. I have used display:flex but it is still showing as a column. What I want is for each button to display the first character of its name underneath it, with all buttons lined up next ...

Encountering a React App 404 Error upon refreshing the webpage

I've encountered an issue with my React application - it works perfectly when initially loaded in the browser, but upon refreshing the page, a 404 Error is displayed. Below is the code for my App.js file. I am still learning React, so any advice or su ...

What is the best way to showcase information retrieved from a Route Handler in NextJS v13.4?

I have successfully utilized the new app router to create a route handler for a GET request and received the data in my console. Now, I am looking to integrate this data into NextJS v13.4. How can I achieve this? Below is the route handler I created to fe ...

The input came to a sudden and unexpected end, we were looking for the }

Is there a solution to the error that occurs when attempting to execute npx flow? ...

Designing a responsive two-column table layout

My current challenge involves a small table structured as a bullet list with two columns. To enhance mobile display, I am seeking a way to collapse it down to a single column: The current implementation includes the following code snippet: <style> @ ...

Populate a Material UI Select Component in real-time based on the current state of other components

I'm facing a specific issue at the moment. I am dealing with two select components provided by Material-UI. The first select component includes car brands, while the second one contains car models. Expected behavior Car brands are fetched from the ...