Styling in React: 5 Ways to Style Your React App

So, you're here to learn about styling in React? Well, you've come to the right place. By the time you finish reading this article, I promise you will know how to do it. In this article, we'll review styling React components using inline styles, styled components, CSS modules, Tailwind CSS, and Sass and CSS stylesheets.

We'll explain these methods using components that are part of the todo application. The pros and cons of the styling options examined in this article are also considered.

What if you are new to React and Google Maps for Android is stuck? There are 9 ways to fix running freezes, you can check the official documents.

Set up your React application

To set up the application, you can use Create React App. This is the easiest way to get started with React projects. However, the CRA demonstration is beyond the scope of this article, what should I do if Win10/11 cannot uninstall the update file? An error occurred and all updates were not successfully uninstalled so we'll skip that and design a fictional to-do application.

Here is a demo of the React application:

Style react components with inline styles

If you're familiar with basic HTML, you know that CSS can be added inline. This is similar in React.

We can add inline styles to any React component we want to render. These styles are written as attributes and passed to the element. What should I do if there is no sound in Windows 11? 12 Ways to Fix No Sound on Your Computer Let's style the component part with inline styles:

/** src/todo/AddTodo.js **/
​
//...code omitted for brevity
const AddTodo = () => {
 //...
  return (
    <div style={
  
  { display: "flex", flexDirection: "column" }}>
      <h2 style={
  
  { padding: "10px 20px", textAlign: "center", color: "white" }}>
        TODO
      </h2>
      <div
        style={
  
  {
          display: "flex",
          justifyContent: "center",
          alignItems: "center"
        }}
      >
        <label
          style={
  
  { padding: "10px 20px", textAlign: "center" }}
          htmlFor="new-todo"
        >
          What needs to be done?
        </label>
      </div>
      <div
        style={
  
  {
          display: "flex",
          justifyContent: "center",
          alignItems: "center"
        }}
      >
        <form onSubmit={handleSubmit}>
          <input onChange={onChange} value={task} ref={inputRef} />
          <button>Add </button>
        </form>
      </div>
      {message && (
        <div
          style={
  
  {
            display: "flex",
            justifyContent: "center",
            alignItems: "center"
          }}
        >
          <h4 style={
  
  { color: "red" }}>{message}</h4>
        </div>
      )}
    </div>
  );
};
export default AddTodo;

In the above code, we have added inline styles to the HTML elements in . Here are some things you should be aware of. AddTodo()

First, there are two braces. The content we're rendering is written in JSX, and for plain JavaScript expressions to be used in JSX, they must be enclosed in braces.

The first curly brace injects JavaScript into the JSX. inner braces create an object

literal. Styles are passed to elements as object literals.

JSX is a preprocessor step that adds XML syntax to JavaScript. You can absolutely use React without JSX, but JSX makes React more elegant. Like XML, JSX tags have a tag name, attributes, and sub-tags.

The next thing to notice is that properties are separated by commas. This is because what we are passing is an object. Because it's a JavaScript property, the properties are camelCase rather than dash-separated.

In the code above, we're just adding some attributes to the element we're styling. However, suppose we have to add more and more styles to an element. This is where the inline method breaks down because it doesn't look clean.

However, there is a way around this problem. We can create object variables and pass them to elements.

Create a style object variable

We create a style object variable just like we create a JavaScript object. This object is then passed to the style attribute of the element we want to style.

Therefore, we did not directly add styles inline like in the previous example, how does the win11 system check the computer configuration? 3 ways to share graphic tutorials but to pass variables directly, as follows: object

/** src/todo/AddTodo.js **/ 
const AddTodo = () => { 
//...
  return (
    <div style={Container}>
      <h2 style={Header}>TODO</h2>
      <div style={LabelContainer}>
        <label style={Label} htmlFor="new-todo">
          What needs to be done?
        </label>
      </div>
      <div style={FormContainer}>
        <form onSubmit={handleSubmit}>
          <input onChange={onChange} value={task} ref={inputRef} />
          <button>Add </button>
        </form>
      </div>
      {message && (
        <div style={Message}>
          <h4 style={
  
  { color:"red" }}>{message}</h4>
        </div><h4 style={
        </div><h4 style={
        </div>
      )}
    </div>
  );
};
​
const Container = { display: "flex", flexDirection: "column" };
const Header = { padding: "10px 20px", textAlign: "center", color: "white" };
const LabelContainer = { display: "flex", justifyContent: "center", alignItems: "center"};
const Label = { padding: "10px 20px", textAlign: "center" };
const FormContainer = { display: "flex", justifyContent: "center", alignItems: "center"};
const ErrorMessage = { display: "flex", justifyContent: "center", alignItems: "center"};

In the code above, we created six object variables: , , , and . Container HeaderLabelContainer LabelFormContainer, ``ErrorMessage

We then pass these variables to the element instead of typing them directly.

We don't have to use double curly braces inside the elements, because the variables themselves are objects.

What to do if you view the object properties Windows 11 search bar does not work? Sharing a graphic tutorial of 7 fixes that will be converted to dash-separated CSS properties during compilation. For example, this: camelCases

backgroundColor: "#44014C",
minHeight: "200px",
boxSizing: "border-box"
In plain CSS, these will be written as:
background-color: #44014C;
min-height: 200px;
box-sizing: border-box;

Dash-separated string changes only apply to attribute names, not attribute values. camelCase

Variables can be passed to properties as values. So, we can do this:

/* in .js file */
const spacing = "10px 20px";
const Header = {
  margin: spacing,
  padding: spacing
  // ...
}

Creating global object variables may be bad practice in many JavaScript environments, but it's fine in React. Since files are not visible to other files unless they are imported, we can create as many object variables as possible without conflicting, even if the names are the same.

Share styles between many React components

Style objects and components don't have to be in the same file. We can create a separate file for our styles, export those styles, and then import them into the components we want to use. Doing this allows styles to be reused across multiple components. Let's do this for our component. .js

First, we'll create a separate file called . We will then add the following styles: .js``styles.js

const Container = { display: "flex", flexDirection: "column" };
const Header = { padding: "10px 20px", textAlign: "center", color: "white" };
const LabelContainer = {
  display: "flex",
  justifyContent: "center",
  alignItems: "center"
};
const Label = { padding: "10px 20px", textAlign: "center" };
const FormContainer = {
  display: "flex",
  justifyContent: "center",
  alignItems: "center"
};
const ErrorMessage = {
  display: "flex",
  justifyContent: "center",
  alignItems: "center"
};
​
export const styles = {
  Container: Container,
  Header: Header,
  LabelContainer: LabelContainer,
  Label: Label,
  ErrorMessage: ErrorMessage,
  FormContainer: FormContainer
}
​
export const styles = {
  Container: Container,
  Header: Header,
  LabelContainer: LabelContainer,
  Label: Label,
  ErrorMessage: ErrorMessage,
  FormContainer: FormContainer
}

In the code above, we can export each style object individually, which also means importing them individually. This can get tedious if you have many style objects in the file.

So it only makes sense to create an object that contains all styles. This object will be exported and imported once to the component that will use it. So, let's do this:

/** AddTodo.js file **/
​
// Import the styles
import {styles} from "./styles";
​
​
const AddTodo = () => {
//....
  return (
    <div style={styles.Container}>
      <h2 style={styles.Header}>TODO</h2>
      <div style={styles.LabelContainer}>
        <label style={styles.Label} htmlFor="new-todo">
          What needs to be done?
        </label>
      </div>
      <div style={styles.FormContainer}>
        <form onSubmit={handleSubmit}>
          <input onChange={onChange} value={task} ref={inputRef} />
          <button>Add </button>
        </form>
      </div>
      {message && (
        <div style={styles.ErrorMessage}>
          <h4 style={
  
  { color: "red" }}>{message}</h4>
        </div>
      )}
    </div>
  );
};

Above, we will import the objects. This object is then used to style our React application's components and is used like any JavaScript object. AddTodo()``styles

pros and cons

The takeaway from this is that styles can be used and reused across multiple components. Just import the styles and add them to the style properties.

Of course, there are some cases where you shouldn't use inline styles, and that's where our next two methods come in.

advantage:

Using inline styles can help you quickly prototype your interface.

shortcoming:

Declarations can get messy and disorganized very quickly, use inline styles. Also, inline styles discourage the DRY (Don't Repeat Yourself) principle. Using inline styles is not suitable for large projects with a lot of code. styles

Use styled components

Using styled components, we can write the actual CSS in the JavaScript file. This means you can use all the power of CSS in JavaScript - like media queries, pseudo-selectors, nesting, etc.

Styled components use ES6's tagged template literals to style components. With it, the mapping between components and styles is removed. This means that when you define your styles, you are actually creating a normal React component with your styles attached to it.

Using styled components, we can create reusable components with styles. Very exciting to create and use.

First, we need to install it by running in the React application's directory. $ npm install --save styled-components

Let's go back to our to-do application and let our components use styled components. First, use .styled-components AddTodo.jsimport styled from 'styled-components';

Now, we can start using it right away. We'll first create a styled component, then see how we'll use it:

/** AddTodo.js file **/
const Container = styled.div`
  display: flex;
  flex-direction: column;
`;
const Header = styled.div`
  padding: 10px 20px;
  text-align: center;
  color: white;
`;
//....

In the above code, we have created a component that can be the same as any React component. However, please note that we use pure CSS in the JavaScript file. Next, let's place this component:

/** AddTodo.js file **/
​
function AddTodo() {
 //...
​
​
return (
    <Container>
      <Header>TODO</Header>
      <LabelContainer>
        <Label htmlFor="new-todo">What needs to be done?</Label>
      </LabelContainer>
      <FormContainer>
        <form onSubmit={handleSubmit}>
          <input onChange={onChange} value={task} ref={inputRef} />
          <button>Add </button>
        </form>
      </FormContainer>
      {message && (
        <ErrorContainer>
          <ErrorMessage>{message}</ErrorMessage>
        </ErrorContainer>
      )}
    </Container>
  );
}

In the above code, we used the styled component we created and replaced the HTML tags with the defined component style tags. Styled components are used as any other HTML element. The only difference is that it comes with its own predefined styles.

You can access the code in the CodeSandbox playground:

pros and cons

To learn more about styled components and how to use them, you can read about it here.

advantage:

Styled components dynamically style elements in any way you see fit. They encourage the use of DRY principles to organize code, and styled components are compatible with various frameworks and libraries. They are also great for developing and maintaining design systems.

shortcoming:

Styled Components incur a significant computational overhead in translating declarations into plain CSS. This may affect application performance. Styled components also require time to get used to the syntax and process.

Next, let's discuss a third way of styling in React.

A CSS module for styling React components

A CSS module is a CSS file in which all class and animation names are scoped locally by default. Make a note of the local scope terms. Let's break it down a bit.

By default, the scope of CSS class names and animation names is global. This can cause conflicts, especially in large stylesheets, since one style can override another. CSS Modules solves this problem. CSS classes are only available in the component that uses them.

A CSS module is basically a compiled file. When compiled, it produces two outputs. One is CSS, a modified input CSS with renamed class names. The other is a JavaScript object that maps the original CSS name to the renamed name. .css

Alright, let's create a CSS class for our example error message in our module. The name of our module is: styles.module.css

.error-message {
  color: red;
  font-size: 16px;
}

When compiled, this produces something like this:

.error-message_jhys {
  color: red;
  font-size: 16px;
}

What was added is just an example key (added by myself) to uniquely identify this class. As mentioned, it generates a JavaScript object that can be imported into a React file and used: jhys

{
  error-message: error-message_jhys
}

Now, let's see how to use:

/** .js file **/
import styles from './styles.css';


function Message() {
 return (
   <div className={styles.ErrorMessage}>I am an error message</div>
 );
}

pros and cons

Remember, the main purpose of CSS Modules is to keep CSS classes in local scope and avoid naming conflicts. Here are some pros and cons of using CSS Modules.

advantage:

CSS Modules can be easily integrated with CSS or SCSS styling engines. They generate unique class names without conflicts and have built-in support in the React library. Fun Notes CSS Module also fixes the global scope issue of CSS declarations.

shortcoming:

Referencing class names with CSS modules can be confusing most of the time.

Styling with Tailwind CSS

Tailwind CSS offers a different approach where there is no need to write CSS to style your application. Instead, Tailwind CSS uses utility classes for each CSS property that you can use directly in HTML or JSX.

Maybe you're wondering if every CSS property maps to a class; what's the final CSS bundle size? In fact, the bundle size is very small, with most projects delivering bundle sizes below 10kB. But how? Tailwind CSS takes the classes you use at build time and builds a custom CSS bundle for your project.

Tailwind CSS offers more than just CSS classes mapped to properties; it's also a complete framework that supports responsive behavior, grids, states, dark mode, and more. Also, it is highly configurable.

To setup Tailwind CSS on a CRA project, several steps (and libraries) are involved. This is because the application's build process needs to be modified to generate the CSS bundle.

First, first install Tailwind CSS and generate and .tailwind.config.js``postcss.config.js

Then, run and command. $ npm install -D tailwindcss postcss autoprefixer``$ npx tailwindcss init -p

Note that all Tailwind CSS-related libraries are installed as packages, which means they won't affect your JavaScript bundle size. dev

In the above generated, add the following value to the array: tailwind.config.js `` content

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{js,jsx,ts,tsx}",],
  theme: {
    extend: {},
  },
  plugins: [],
}

Now, we need to set our CSS baseline. Since Tailwind CSS uses multiple classes with relative values, it's important to have the same CSS styling library in all browsers. Tailwind CSS comes with some default styles to do just that.

To do this, please navigate to your file and paste the code: src/index.css

/* ./src/styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

Note that importing these classes will make all default elements behave differently than expected, so elements like headings and paragraphs will have the same style attributes until you add the Tailwind CSS classes to them.

Tailwind CSS offers many configuration options during setup, so check out the official documentation if you want to learn more.

Finally, use the Tailwind CSS classes in your project. With your setup ready, you can now use CSS classes directly on your project. Continue building a component with Tailwind CSS: ToDo

/** AddTodo.js file **/

function AddTodo() {
 //...

  return (
    <div className="flex flex-col">
      <h2 className="px-2.5 py-5 text-center text-white">TODO</h2>
      <div className="flex justify-center items-center">
        <label className="px-2.5 py-5 text-center" htmlFor="new-todo">
          What needs to be done?
        </label>
      </div>
      <div className="flex justify-center items-center">
        <form onSubmit={handleSubmit}>
          <input onChange={onChange} value={task} ref={inputRef} />
          <button>Add </button>
        </form>
      </div>
      {message && (
        <div className="flex justify-center items-center">
          <h4 className="text-red-800">{message}</h4>
        </div>
      )}
    </div>
  );
}

Note that these classes are injected directly into props as text, and there is a full reference to all class names with state and response properties that can be used. className

pros and cons

While it may seem counterintuitive at first, once you've used Tailwind CSS for a few days, you'll likely love it. Let's take a look at some pros and cons of Tailwind CSS.

advantage:

Tailwind CSS is easy to use for customizing elements and building clean user interfaces. Tailwind CSS greatly reduces writing custom CSS code, which allows you to develop UI screens faster.

shortcoming:

Tailwind CSS usually requires you to implement it from scratch, since basic components like buttons, navbars, and tabs are not provided. Also, learning Tailwind CSS requires a minimal learning curve.

Sass and CSS stylesheets in React

Sass (Syntactically Awesome Stylesheets) is a CSS preprocessor with many features for creating reusable styles, nesting functions, and organizing CSS declarations. Use Sass or CSS stylesheets based on writing styles in external files and importing them into components that require it.

In summary, Sass is all about writing standard CSS with the added bonus of being good. Additionally, you can write styles using Sass or SCSS syntax.

This guide uses SCSS syntax to demonstrate its use in a to-do application.

To get started, use the command to add development dependencies to your project. Also, please update the file with the file extension. node- npm install node-sasssass.css``.scss

In the code below, you will see a mix of CSS and SCSS syntax. The SCSS engine allows writing plain CSS while also taking advantage of its additional features:

/** todo.scss file **/

// declare global variables
$paddingVertical: 10px;
$paddingHorizontal: 20px;
$text-center: center;
$text-white: #ffffff;
$text-black: #000000;
$text-red: rgb(185 28 28);
$font-size: 16px;
.error {
  color: $text-red;
}
.container{
  display:flex;
  flex-direction: column;
}
.flex-center {
display: flex;
justify-content: center;
align-items: center;
}
%typo-large {
  padding: $paddingVertical $paddingHorizontal;
  text-align: $text-center;
}
.h2 {
 @extend %typo-large;
 color: $text-white;
}

.label {
 @extend %typo-large;
}

Next, import the style declarations into the component. So, in the file, import the contents of the file, and then you can access the styles like this: AddTodo``todo.scss

/** AddTodo.js file**/

//...imports omitted for brevity

// Import the styles
import "./todo.scss";


function AddTodo() {
 //...code omitted for brevity
return (
    <div className="container">
      <h2 className="h2">TODO</h2>
      <div className="flex-center">
        <label className="label" htmlFor="new-todo">
          What needs to be done?
        </label>
      </div>
      <div className="flex-center">
        <form onSubmit={handleSubmit}>
          <input onChange={onChange} value={task} ref={inputRef} />
          <button>Add </button>
        </form>
      </div>
      {message && (
        <div className="flex-center">
          <h4 className="error">{message}</h4>
        </div>
      )}
    </div>
  );
}

Here is the CodeSandbox playground for the example above:

pros and cons

Let's consider some pros and cons of Sass and CSS style sheets.

advantage:

Sass and CSS stylesheets have extensive capabilities for dynamically styling user interfaces and have a large user and support community. Sass and CSS stylesheets allow you to easily integrate with standard CSS code.

shortcoming:

Unfortunately, learning Sass and CSS stylesheets comes with a steep learning curve, and Sass and CSS stylesheets require some effort to structure and organize SCSS code.

What's the best way to style things in React?

While many libraries and CSS engines provide ways to style React applications, it's important to note that this is not a general approach to optimal React styling solutions.

With that in mind, several factors vary from software team to software team when it comes to finding the best way to style a React application. Here are some considerations:

  • What are performance indicators?

  • How easy is it to optimize your code?

  • Do you need a design system?

  • Does the CSS system require extra effort to customize your UI?

These are some of the questions you need to answer before summing up the best styles in React. Ultimately, the team plays an important role in choosing the CSS solution that best fits the product requirements, taking into account the team's expertise and domain knowledge.

Now, it's clear that there is no straight-forward answer to choosing the best library, framework, or system to style a website built with React. However, this article outlines five great ways to style things in React.

Go ahead and explore what works for you or your team; you may be satisfied with any of the CSS solutions discussed in this article.

in conclusion

So, there we have it - five ways of styling in React. In general, all methods are useful, depending on the size of the project; you can use any one.

Guess you like

Origin blog.csdn.net/weixin_47967031/article/details/132646520