Tips for preventing the use of inline styling in React

I am facing an issue with some variables set at the top of my functional component that are not being used except in styles:

const testWidth = 100;
const testHeight = 100;

Although I use some of these variables in my styles...

I am considering moving my styles to another file, related to a class name like '.divWrapperStyle', but I'm unsure about how to interact with the variable 'testWidth'

<div
style={{
  borderBottom: 0,
  width: `${testWidth}px`,
  width: 'auto',
  paddingRight: 0,
  paddingLeft: 0,
  paddingTop: 20,
}}
>

I am thinking of creating a separate .css file like this:

.wrapper{
    borderBottom: 0,
    paddingRight: 0,
    paddingLeft: 0,
    paddingTop: 20,
 }

After importing that file, I might use something like:

 <div className="wrapper> 

But how can I include the value of testWidth for the width property?

The variables used in CSS are causing some difficulties for me :/

Any suggestions on how to address this issue would be greatly appreciated!

Answer №1

If you're in search of a solution, the styled-components library is worth considering.

When it comes to using traditional CSS, it's important to shift your perspective. Focus on defining the style variations you want to support rather than passing arbitrary numerical values to your CSS.

You can create variations like wrapper--mobile, wrapper--tablet, wrapper--desktop, or even just a single modification such as wrapper--wide following the BEM notation.

In the second approach, utilize media queries for dimension calculations (mobile vs. tablet) and JavaScript truthy-calculations using a tool like clsx to generate class names that represent the variants you want to support in your CSS.

If compatible with your browser stack, consider using CSS variables. Remember to focus on declaring the set of variations you need to support in one place for easy adjustments in the future, rather than focusing on passing arbitrary numerical values.

I hope these options bring you closer to achieving your desired outcome. Let me know if you need further assistance.

Answer №2

Instead of adding inline styles repeatedly, consider creating a separate .JS file named style.js for better organization. Here's an example of how you can structure it:

const testWidth = 100;
const testHeight = 100;

export default const styles = {
   divWrapperStyle: {
     borderBottom: 0,
     width: testWidth, // utilize variables
     width: 'auto',
     paddingRight: 0,
     paddingLeft: 0,
     paddingTop: 20,
   }
}

To use these styles in your functional component, simply import them like this:

import styles from '{pathToStyle.jsFile}';

Then, apply the styles to your elements like so:

<div style={styles.divWrapperStyle}>

By following this approach, you can easily adjust styles dynamically without relying on external libraries. It's a simple and efficient solution.

Answer №3

Instead of adding another library, you can simply move the styles to a separate file and import them as constants, with default values specified for any values that may need to be changed.

Then, if you need to update or change a property, you can easily do so by spreading in the new value:

// styles.js
export const myStyles = {
  borderBottom: 0,
  width: `10px`,
  width: 'auto',
  paddingRight: 0,
  paddingLeft: 0,
  paddingTop: 20,
}

Here's how you can use it:

// MyComponent.js
import {myStyles} from ... 

<div style={{...myStyles, width: `${newWidth}px`}}>

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

Content creator: Enhancing HTML search functionality using parameters

Hey there, I'm facing an issue. I created a template on my Blogger site and I need to search for text with a specific label using this URL: www.my_blog.blogspot.com/search?q=label:Printers+SearchText This is the code I have: <form action=&ap ...

What is the term used for a tag that automatically closes itself?

Within tag-based languages such as HTML or XML, there are tags that automatically close themselves without the need for a separate closing tag: <tag/> As opposed to the traditional method of closing tags like this: <tag></tag> Do thes ...

Creating a Star Rating System Using HTML and CSS

Looking for help with implementing a Star rating Feedback on articles in Visualforce page. Came across some code that seems to fit the bill but facing issues with getting it to work when placed in a file and executed, particularly in Firefox. Any assistanc ...

Styled-Component: Incorporating Variables into Styled-Component is my goal

Currently, I am working on an app and have created a separate file for styling. I decided to use style-components for custom CSS, but faced an issue where I couldn't access variables instead of HEX values. Even after storing color values in a variable ...

Tips for establishing a custom thumbnail and title for HTML audio or video in the Chrome media control menu and Windows media control dialog

Is there a way to display the thumbnail and title of audio or video in HTML in the Chrome media control menu and Windows media control menu (where a dialog appears when the volume up or down key is pressed)? Chrome Menu https://i.sstatic.net/oLDgK.png W ...

Animate CSS Grid to dynamically fill the viewport on top of current grid elements

Please note that I am specifically seeking vanilla JS solutions, as jQuery is not compatible with this project I have a grid structure that is somewhat complex: body { margin: 0; height: 100vh; text-align: center; } .grid-container { ...

Desktop Safari displays Font-awesome icons with trimmed corners using a border-radius of 50%

While working on incorporating font awesome share icons into my project, I encountered an issue with getting a circle around them. After exploring various approaches, I opted for a CSS solution. Using React FontAwesome posed some challenges that led me to ...

Processing .obj file and converting it into a string format with the help of three

I have a unique challenge where my program creates .obj files at runtime and stores them as strings. I am now looking to load these generated .obj files using the load() function in three.js (OBJLoader). Currently, the load() function uses an HTTP request ...

Setting the root position of a div: How can it be done?

Imagine a scenario where a div element is designed to follow the mouse cursor on the screen. This functionality is achieved by manipulating the document's `mousemove` event and adjusting the div's `left` and `top` positions based on the event dat ...

Error message from Commitlint: Uncaught ReferenceError: module is not defined within an ES module environment

If you're looking to kickstart your open source projects, I've set up a starter project equipped with commitlint, release-it, and more. Check it out here! To get started, simply clone the project with this command: git clone https://github.com/ ...

Obtaining the sum of two variables from two separate functions results in a value of NaN

Why is it that I'm seeing a NaN result when trying to access a variable in two different functions? This is my code var n_standard = 0; var n_quad = 0; var totalQuad; var totalStandard; var total = totalStandard + totalQuad; ...

Is it possible to add data in MongoDB without specifying a field name?

I have a couple of queries that revolve around the same concept: If I want to insert a new 'row' in MongoDB, can I do so by specifying the order of the fields? For instance, if my collection looks like items = { { name: "John", age: "28" ...

Inserting a custom text box underneath the Anything Slider

I am currently incorporating the Anything Slider into a website project. The main purpose of the slider is to showcase videos, but I would like to include a description text box beneath it that dynamically changes based on the selected tab. This snippet de ...

The harmonious combination of Opera and XMLHttpRequest creates a

Coming from Russia, please excuse any mistakes in my English. I am trying to dynamically load the main page of my website using JavaScript, and I have written this script: <script type="text/javascript"> function httpGet(theUrl) { var xmlHt ...

Dynamic Bodymovin motion graphics

I'm trying to figure out the best way to embed a bodymovin exported file on my website so that it is responsive, maintains the correct aspect ratio of the logo and fonts, and fits within the borders of the site. Does anyone have any suggestions? Appr ...

Navigate back to the previous route within the Vue router hierarchy

In my Vue application, I have a Settings page with child routes such as settings/user, settings/addUser, etc. I am looking to implement a back button that when pressed, takes the user back to the specific page they visited within the Settings section. Usin ...

It appears as though the promise will never come to fruition

I am currently developing an application that is designed to search for subdomains related to a specific domain and store them in a database. The application retrieves data from crt.sh and threatcrowd. One of the functions within the application parses th ...

When using React, draggable components with input fields may lose their ability to receive focus when clicking on the input field

<Draggable axis="y" grid={[135,135]} onStop={this.handleStop} defaultPosition={{x: this.props.task.positionX, y: this.props.task.positionY,}}> <div id="edit-task-component"> <form onSubmit={this.handleSubmit} id=" ...

My confidential environment variables are being inadvertently revealed to the client by Next.js

I am encountering a problem with my project in which an environment variable is being revealed to the browser. Despite the documentation stating that only environment variables prefixed with NEXT_PUBLIC_ should be accessible in the browser environment, all ...

What is the best way to extract data from a JavaScript object received from multer?

Currently, I am facing an issue while trying to utilize multer for handling the upload of a CSV file in Express. The goal is to parse the uploaded file line by line. Although I can successfully retrieve the file as an object stored in req.body, I encounter ...