We all know how to link a stylesheet to an HTML , but styling in a React single-page application (SPA) offers more options. Let's explore the various approaches to CSS in React, highlighting their strengths and weaknesses.
This method mirrors traditional CSS linking.
style.css
).import "./style.css";
Example:
import React from "react"; import "./Components/css/App.css"; function App() { return ( <div classname="main"> </div> ); } export default App;
This imports App.css
from the /Components/css
folder.
While generally discouraged for large projects due to maintainability concerns, inline styles can be practical in specific contexts. React's component structure mitigates some maintainability issues.
A simple example:
<div classname="main" style="{{" color:> </div>
A more organized approach uses style objects:
import React from "react"; function App() { const styles = { main: { backgroundColor: "#f1f1f1", width: "100%", }, inputText: { padding: "10px", color: "red", }, }; return ( <div classname="main" style="{styles.main}"> </div> ); } export default App;
This applies styles defined in the styles
object. Note the use of curly braces for object referencing.
CSS Modules offer locally scoped class names, preventing naming conflicts in larger applications. Each component gets its own unique class names.
.module.css
file (e.g., styles.module.css
).className
:/* styles.module.css */ .font { color: #f00; font-size: 20px; }
import React from "react"; import styles from "./styles.module.css"; function App() { return ( <h1 classname="{styles.font}">Hello World</h1> ); } export default App;
Styled-components provides a way to write actual CSS within your JavaScript, creating styled React components. Benefits include unique class names, dynamic styling, and better CSS organization.
Install: npm install styled-components
Import: import styled from 'styled-components';
Example:
import React from "react"; import styled from "styled-components"; const Wrapper = styled.div` width: 100%; height: 100px; background-color: red; display: block; `; function App() { return <wrapper></wrapper>; } export default App;
Styled-components allows conditional styling using props within the CSS, enabling dynamic style changes based on component state or props. This example uses a ternary operator for conditional styling:
(Example code demonstrating conditional styling omitted for brevity, but the concept is explained.)
React offers diverse CSS styling options. The best approach depends on project size, complexity, and personal preference. This overview provides a solid foundation for choosing the right method for your React projects.
The above is the detailed content of Different Ways to Write CSS in React. For more information, please follow other related articles on the PHP Chinese website!