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

Experiencing a problem while attempting to start an Android React Native project

Whenever I try to execute the react-native run-android command, the following message appears: info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag. Jetifier found 998 file(s) to forward-jetify. Using 12 wo ...

What is the best way to address background-image overflow on a webpage?

I'm facing a challenge in removing the overflow from a background-image within a div. There are 4 divs with similar images that combine to form one background image (I adjust the position of each image so they align across the 4 divs). Essentially, I ...

When opening a dialog at the bottom of the page, the window will automatically scroll to the top

I'm encountering an issue with a page that has a width exceeding 100% (2000px). Whenever I click to display a dialog from a button located at the end of the horizontal page, the window automatically scrolls back to the beginning of the page before sho ...

The focus of Material v5 UI is on maintaining a clear and strict division of

In the past, I had centralized themes and styles in a file named themes.js while using v4 of Material UI. All styled components were placed under a single useStyles function. As I transition to Material v5, I want to continue centralizing everything while ...

Bootstrap tab toggle feature

I'm currently facing an issue with Bootstrap's tab component. I need help figuring out how to hide a lorem ipsum section and show a hidden div when a specific tab is clicked, and then revert the changes when a different tab is selected. $(func ...

An HTML/CSS component that dynamically adjusts its height at random intervals

My goal is to have the footer of my page occupy just one line in height. On occasion, when I open my page in a new browser tab, the footer ends up being two lines tall. However, if I simply reload the page within the same tab, everything appears as intende ...

An issue has been identified where a single image is not displaying properly on Android devices, as well as IE7 and

Hey there! I recently created a Wordpress site and it seems that the Art Below logo isn't appearing in IE7, IE8, and Android for some reason. Would anyone be willing to help troubleshoot this issue? If you have fresh eyes, please take a look at the f ...

How can I ensure that my rendering only occurs after a full input has been entered? Implementing a delayed render() in ReactJS

Im working on a form that includes Controlled Component text inputs: <input type="text" onChange={(e) => this.props.changeBusiness(e)}/> I'm thinking of rendering the above text input in a separate component. It would be great if I could re ...

Verify if the second list item contains the "current" class

When displaying a list of blog items on the blog page, I am using grid-column: 1 / -2;. In the first row, the first blog item spans two columns while the second and subsequent rows display three items in each row. This setup works well, but when moving to ...

The onSubmit event handler seems to be malfunctioning within a Reactjs form

I recently started using React and encountered an issue with my form: class CustomForm extends React.Component { handleFormSubmit = (e) => { e.preventDefault(); const title = e.target.elements.title.value; const content = e ...

A step-by-step guide to showing images in React using a JSON URL array

I successfully transformed a JSON endpoint into a JavaScript array and have iterated through it to extract the required key values. While most of them are text values, one of them is an image that only displays the URL link. I attempted to iterate through ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

A guide on implementing a callback function with the iTunes search API

I am having trouble setting up a callback function to effectively utilize the iTunes Store search API. My goal is to achieve the following behavior: const getiTunes = fetch(`https://itunes.apple.com/search?term=${search}&media=movie&limit=200`) ...

Zod vow denial: ZodError consistently delivers an empty array

My goal is to validate data received from the backend following a specific TypeScript structure. export interface Booking { locationId: string; bookingId: number; spotId: string; from: string; to: string; status: "pending" | "con ...

Having trouble changing a state from a class component to a function component in React

I've been updating my React projects by converting all my classes to functions. However, I encountered an issue where ESLint is reporting a parsing error in my code. Oddly enough, if I remove just one line, the error disappears. Here's the snippe ...

Concealing/Revealing Elements with jquery

For hours, I've been attempting to switch between hiding one element and showing another in my script. Here is the code I am using: <script type="text/javascript"> function () { $('#Instructions').hide(); $('#G ...

The date format is malfunctioning -> Error: The date provided is not valid

My goal is to convert the date format from 2022-01-17T21:36:04.000Z to January 18th using the npm package, dateFormat. I found success with the following code snippet: const date = dateFormat("2022-01-17T21:36:04.000Z", "mmmm dS"); However, when trying t ...

How to clear input fields in Ant Design ReactJS components

Utilizing the form list component from antd in my react.js project https://ant.design/components/form/#Form.List I have a basic form list set up where I can easily add or remove fields. At times, I need to reset the form and remove any additional items t ...

Using dynamic loading in NextJS, how can one access the ReactQuill Ref?

Currently facing an interesting issue. I am making use of NextJS for its server-side rendering abilities and incorporating ReactQuill as a rich-text editor. To work around ReactQuill's connection to the DOM, I am dynamically importing it. However, thi ...

Switch between light and dark themes in antd using React at runtime

Despite finding a similar question on Stack Overflow, the provided answer did not solve my issue. I have attempted to follow the steps mentioned, but unfortunately, there has been no noticeable effect. I am struggling with where to place the config-overrid ...