Course Content
Expert React
Expert React
4. Formik
6. Next Steps
Approaches to Styling in React Apps
Key concepts to remember
- 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.
- 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.
- 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 theclassName
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 thedefault 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 andList.module.css
file - Add the class name
list
to the<ul>
element - Add the class name
item
to each<li>
element
Everything was clear?