React element featuring various interfaces

Currently, I am working on styling a React component in a way that allows for either horizontal or vertical styling without using flexbox.

My question is, how can I pass styles down to the component in a way that applies individual styles to the child elements of the component?

For example, to achieve https://i.sstatic.net/rp6nh.png

and

https://i.sstatic.net/PHEu7.png

The styles specific to the horizontal layout are:

input, button {
    vertical-align:middle;
}

button {
    margin-left: 10px;
}

while those specific to the vertical layout are:

.form-control {
    display: inline-block;
}

.btn {
    display: block;
    margin: auto;
}

Here is an example of the component:

class Form extends React.Component {

  render () {
    return (
      <form className="form-group">
        <input className="form-control" type="text" placeholder="St. George, Utah"/>
        <button className="btn">Get Weather</button>
      </form>
    );
  }
}

Answer №1

There are a few strategies you can use to tackle this issue.

One approach involves following Michael Lyons' advice. You can pass a prop to the component that dictates if the layout should be vertical or horizontal.

With this variable in hand, you can apply specific classes to style your component according to your preferences.

Your component could be structured like this:

class Form extends React.Component {

  render () {
    let buttonClassName = "btn" + (this.props.isVertical)? " vertical-button" : "horizontal-button";
    let inputClassName = "form-control" + (this.props.isVertical)? " vertical-input": "hotizontal-input";
    return (
      <form className="form-group" >
        <input className={inputClassName} type="text" placeholder="St. George, Utah"/>
        <button className={buttonClassName} >Get Weather</button>
      </form>
    );
  }
} 

The CSS styling for the form could resemble the following examples:

/* Styles for the vertical form */

.vertical-input {
    display: inline-block;
}

.vertical-button {
    display:  block;
    margin: auto;
}

/* Styles for the horizontal form */

.horizontal-input, .horizontal-button {
    vertical-align:middle;
}

.horizontal-button {
    margin-left: 10px;
}

Another option is to pass a style object directly to the HTML tags using the style attribute, based on the flag you receive. For instance, if you receive this.props.isVertical, you can create a JS object like this:

let inputStyle = { display: "inline-block" };

You then pass it to the tag as follows:

<input className="form-control" type="text" style={inputStyle} placeholder="St. George, Utah" />

Note: When passing objects to HTML tags, the keys should be camelCased instead of separated by dashes. For example, margin-left becomes marginLeft.

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

Tips for modifying the value of an MUI DatePicker in Jest (x-date-pickers)

When it comes to { DatePicker } from '@mui/x-date-pickers': I'm facing a challenge in changing the value using Jest. Let me show you my custom wrapper for DatePicker called DatePickerX: import React, { useState } from 'react'; im ...

How to modify the background image of a div using CSS from a specific folder

<head id="Head1" runat="server"> <title>Title</title> <style> .parallax { /* The image used */ background-image: url(Pictures/BackUS.png); height: 100%; /* Create the parallax scrolling effect */ back ...

Styles brought in from external sources do not get applied to components

My goal is to create a separate file specifically for storing styles targeted at IE 9-11. In order to achieve this, I have created a file named InternetExplorer.scss and imported it into my main file styles.scss: @import "scss/InternetExplorer.scss"; The ...

Is there a way to adjust the positioning of an image within a <div> element?

I'm attempting to vertically align an image within a horizontal menu bar. My goal is to adjust the padding/margin of the image using inline CSS. However, I've noticed that when I add margin-top or padding-top, it affects the positioning of all m ...

transfer information between different express middleware functions within a universal react application

I am working on an isomorphic react app and I am looking for a way to pass state between express middleware functions. One of my express routes handles form submission: export const createPaymentHandler = async (req: Request, res: Response, next: NextFun ...

Updating field values in Graphcool mutations that are not intended to be changed

I encountered an issue with mutation while using Graphcool and Apollo Client in my application. The problem arises when implementing a soft delete functionality, where the user triggers a delete action and the mutation changes only one field in the databas ...

Solve TypeScript React error TS(2339) by resolving issues with extending a React.FC and using static property of type JSX.Element for uninitialized components

Currently, in VSCode, the typescript compiler is at TypeScript React 4.4.2 and it's pointing to a TS(2339) error: Property 'Col' does not exist on type 'FC<GridProps>'. I have attempted to add this prop to GridProps: export ...

Which is better for a React app theme: using material-ui makeStyles or SCSS architecture?

Recently, I became a part of a group working on a React application. Our current approach involves using Material UI and its makeStyles function for styling the app. One of my upcoming responsibilities is to determine the global theme for our project. Pers ...

Ensure that all Woocommerce products have consistent height while allowing for variations in width

I am struggling with achieving consistent height for all the products on my website, while allowing for variable widths. I attempted to resolve this using UI, but unfortunately it was unsuccessful. Does anyone have suggestions on how to accomplish this u ...

React-onclickoutside does not function properly within an iframe

I have developed a custom drop-down list using reactjs. I utilized react-onclickoutside to recognize clicks outside the list and close it. While this method works effectively, it does not respond to clicks within an iframe. import onClickOutside from &apo ...

sending out actions from within deeply embedded functions in redux-saga

Upon form submission, I aim to present users with multiple sequential modals for interaction. This is how my app is structured: To display a modal, simply dispatch an action with the modal content as the payload. dispatch({type: SHOW_MODAL, payload: < ...

What is the best way to incorporate width adjustments in an image source for a responsive website?

Currently learning CSS and experimenting with it on an HTML page. For reference, I'm using this link. Encountering an issue with a responsive header image that adjusts size based on device (small on mobile, large on desktop). Is it possible to achiev ...

Enhance the functionality of Immutable.js field by integrating a custom interface in Typescript

Imagine a scenario where the property name is field, essentially an immutable object. This means that methods like field.get('') and other immutable operations are available for use. Nevertheless, I have my own interface for this field which may ...

Even after dynamically removing the class from the element, the Click event can still be detected

My buttons have a design like this: <a class="h-modal-btn branch-modal-btn"> Buy Now </a> The issue arises when I need to remove certain classes and add attributes to these buttons based on the query string in the URL. Skipping ahead ...

What are the specific constraints for CSS within web components?

<html> <style> body { color: blue; } </style> <body> <h1>Styles!</h1> <p>someone created a very general selector</p> <isolated-stuff></isolated-stuff> </body> <s ...

Choosing img tag titles or alts within td elements using Selenium in C#

In my current setup, there is a table with five columns. The fifth column contains an image icon that changes randomly based on backend data. This image does not have a static id or class. The CSS for this setup looks like this: Using the code below, I w ...

Having issues with nth-child? It seems like nth-of-type isn't working either

I am trying to change the color of all even titles from h2 to orange using nth-child. However, I seem to have made a mistake somewhere and can't figure out what it is... *{ font-size: 1em; } h2{ font-size: 1.5em } ...

Developing a React-based UI library that combines both client-side and server-side components: A step-by-step

I'm working on developing a library that will export both server components and client components. The goal is to have it compatible with the Next.js app router, but I've run into a problem. It seems like when I build the library, the client comp ...

How can I center a <a> vertically within a list that has varying heights?

Help Needed: Alignment Issue with Anchor Tags in List I am facing a challenge with vertically aligning the anchor tags inside my list. The number of list items varies based on the pages of my website, so I have used display flex on the list and flex: 1 on ...

Broken styles when using Material UI with babel and the 'with styles' feature

We've implemented babel and lerna to maintain specific elements of our react web app separately. While the setup has been effective thus far, we're encountering styling issues when generating the static build. The main project is not processed t ...