Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Approaches to Styling in React Apps | React Key Concepts
Expert React
course content

Conteúdo do Curso

Expert React

Expert React

1. React Key Concepts
2. React Router
3. Redux Toolkit
4. Formik
5. Jest
6. Next Steps

bookApproaches to Styling in React Apps

Key concepts to remember

  1. Inline Styles: Inline styles allow us to define component styles directly within the JSX code. They are scoped to the specific component, ensuring that styles don't affect other components.

  2. Styling with a Single CSS File: This approach follows traditional web development practices. We include a global CSS file that can define styles for the entire application. We can achieve consistent styling across components by using class names in JSX and associating them with corresponding styles in the CSS file.

  3. CSS Modules: CSS Modules have become popular for styling in React. They provide local scoping of CSS styles by generating unique class names for each component. This prevents style leakage and conflicts between components. Class names are transformed into unique identifiers during the build process to ensure the correct styles are applied at runtime.

Example

Let's create a component and apply styles using CSS Modules:

Code explanation:

  • Line 2: We import the file containing the styles and assign the word styles to represent that file.
  • Line 4: The code defines a React functional component named Info.
  • Lines 5-10: The component renders HTML markup. We use the className attribute to assign a class to the HTML element, allowing us to apply styles. The value of the className attribute is set to the word representing the styles file (styles), followed by the desired class name.
  • Line 13: The Info component is exported as the default export, allowing it to be imported and used in other application parts.

Complete code

Challenge

We have the source. We have the component List and also, this component has some styles List.module.css. However these files are not connected.

The task is:

  • Connect List.jsx file and List.module.css file
  • Add the class name list to the <ul> element
  • Add the class name item to each <li> element

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 3
We're sorry to hear that something went wrong. What happened?
some-alt