styled-jsx is a CSS-in-JS library that provides scoped styling for React components, primarily built for Next.js, but can also be used with plain React projects. It is very straightforward and integrates seamlessly with the component-based architecture of React.
Here are various examples to help you understand how to use styled-jsx in different scenarios.
1. Basic Styling in a React Component
In this basic example, you’ll add styles directly inside the component using styled-jsx.
BasicStyling.js
import React from "react"; const BasicStyling = () => { return ( <div> <h1 className="title">Hello, styled-jsx!</h1> <p>This is a paragraph styled with styled-jsx</p> {/* Styling within the component */} <style jsx>{` .title { color: blue; font-size: 2em; } p { color: gray; font-size: 1.2em; } `}</style> </div> ); }; export default BasicStyling;
Output:
In this example:
- The styles are scoped to the BasicStyling component automatically.
- The
<style jsx>
block inside the component is where the styles are written.
2. Dynamic Styling with Props
You can pass props to style elements dynamically.
DynamicStyling.js
import React from "react"; const DynamicStyling = ({ color }) => { return ( <button className="btn"> Click Me <style jsx>{` .btn { background-color: ${color || "green"}; color: white; padding: 10px 20px; border: none; border-radius: 5px; color: blue; } `}</style> </button> ); }; export default DynamicStyling;
MyApp.js
import React from "react"; const MyApp = () => { return ( <div> <Button color="blue" /> <Button color="red" /> </div> ); }; export default MyApp;
In this example:
- The Button component dynamically sets the
background
color based on thecolor
prop passed to it.
3. Global Styles
Although styled-jsx provides scoped styling, you can also create global styles using the global
keyword inside the style jsx block.
GlobalStyles.js
import React from 'react' const GlobalStyles = () => { return ( <div> <h1>Styled-jsx with Global Styles</h1> <p>This paragraph is styled globally.</p> <style jsx global>{` body { background-color: lightgray; } h1 { color: darkblue; } p { font-size: 1.2em; color: darkgray; } `}</style> </div> ); } export default GlobalStyles
Output:
In this example:
- The global styles are applied to the
body
,h1
, andp
elements. These styles will affect the whole page, not just the component.
4. Using Nested CSS
You can also write nested CSS in styled-jsx, just like in traditional CSS.
NestedCSS.js
import React from "react"; const NestedCSS = () => { return ( <div className="card"> <h2>Card Title</h2> <p>Card Content</p> <style jsx>{` .card { background-color: white; border: 1px solid #ccc; padding: 20px; border-radius: 8px; } .card h2 { color: darkblue; } .card p { color: gray; } `}</style> </div> ); }; export default NestedCSS;
Here:
- The
card
class styles the outer container, and nested styles are used forh2
andp
inside.card
.
5. Media Queries
You can also use media queries within styled-jsx.
MediaQueries.js
import React from 'react' const MediaQueries = () => { return ( <div> <h1>Responsive Design</h1> <p>This text changes size based on the screen width.</p> <style jsx>{` h1 { color: blue; font-size: 2em; } p { color: gray; font-size: 1.2em; } @media (max-width: 600px) { h1 { font-size: 1.5em; } p { font-size: 1em; } } `}</style> </div> ); } export default MediaQueries
In this example:
- The font sizes for
h1
andp
adjust when the screen width is600px
or less.
6. Handling Conditional Styles
You can apply styles conditionally based on component state or props.
ToggleButton.js
import React, { useState } from 'react'; const ToggleButton = () => { const [toggled, setToggled] = useState(false); return ( <button onClick={() => setToggled(!toggled)} className={toggled ? 'on' : 'off'}> {toggled ? 'ON' : 'OFF'} <style jsx>{` button { padding: 10px 20px; font-size: 1.2em; cursor: pointer; border-radius: 5px; } .on { background-color: green; color: white; } .off { background-color: gray; color: white; } `}</style> </button> ); }; export default ToggleButton;
In this example:
- The button changes its background color based on the
toggled
state.
7. Using Style JSX for Animations
You can easily implement CSS animations within your components using styled-jsx. This can be used to animate elements on user interaction or when the component mounts.
AnimationsStyles.js
import React, { useState } from "react"; const AnimationsStyles = () => { const [isAnimated, setIsAnimated] = useState(false); const toggleAnimation = () => { setIsAnimated(!isAnimated); }; return ( <div> <button onClick={toggleAnimation}>Toggle Animation</button> <div className={`box ${isAnimated ? "animated" : ""}`} /> <style jsx>{` .box { width: 100px; height: 100px; background-color: blue; transition: transform 0.3s ease-in-out; } .animated { transform: rotate(45deg); } `}</style> </div> ); }; export default AnimationsStyles;
In this example:
- The box will rotate when the button is clicked, triggered by adding or removing the animated class.
8. Multiple Style Blocks within One Component
You can have multiple style blocks within one component. This is useful when you need to apply different styles to different sections of the component.
MultiStyleComponent.js
import React from 'react'; const MultiStyleComponent = () => { return ( <div> <h1>Main Title</h1> <p>This is the main content.</p> <div className="footer"> <p>Footer Content</p> </div> <style jsx>{` h1 { color: blue; font-size: 2em; } p { color: gray; } `}</style> <style jsx>{` .footer { background-color: lightgray; padding: 10px; margin-top: 20px; } .footer p { color: darkgray; } `}</style> </div> ); }; export default MultiStyleComponent;
In this example:
- Here, multiple style jsx blocks are used to apply styles to different sections (
h1
,p
, and.footer
).
9. Handling Hover Effects
You can easily add hover effects with styled-jsx for interactive components.
HoverBox.js
import React from 'react'; const HoverBox = () => { return ( <div className="box"> Hover over me! <style jsx>{` .box { width: 200px; height: 200px; background-color: lightblue; display: flex; justify-content: center; align-items: center; font-size: 1.5em; text-align: center; transition: background-color 0.3s ease; } .box:hover { background-color: orange; } `}</style> </div> ); }; export default HoverBox;
In this example, the background color of the box changes when the user hovers over it.
10. Using Theme or Variables for Customization
Although styled-jsx doesn’t have built-in theming, you can implement your own theme by using props or a context provider.
import React from 'react'; const ThemeProvider = ({ children, theme }) => { return ( <div className={`theme-${theme}`}> {children} <style jsx>{` .theme-light { background-color: #fff; color: black; } .theme-dark { background-color: #333; color: white; } `}</style> </div> ); }; const App = () => { return ( <ThemeProvider theme="dark"> <div> <h1>Themed App</h1> <p>This app changes theme based on the provider.</p> </div> </ThemeProvider> ); }; export default App;
In this example:
- The
ThemeProvider
component wraps children and applies different styles based on the theme prop.
Advantages of Using styled-jsx
Simplicity: It’s lightweight and does not add any additional complexity to your codebase. For teams that prefer simple, declarative CSS within their components, styled-jsx might be a good choice.
Automatic Integration with Next.js: If you’re building a Next.js application, styled-jsx comes out-of-the-box with support for server-side rendering (SSR) and static site generation (SSG), and it integrates seamlessly with Next.js features like dynamic imports and page-based routing.
Limitations of Using styled-jsx
Limited CSS Features: styled-jsx offers basic CSS support and allows for nesting and global styles, but it lacks the advanced features offered by other libraries like styled-components.
Difficulty Managing Large Stylesheets: If your stylesheets become large, managing them can be challenging. Since styled-jsx styles are scoped per component, large projects with many components may lead to a large number of <style jsx>
tags distributed across the codebase. This can make it difficult to maintain and refactor styles efficiently.
Conclusion
styled-jsx is primarily designed for use in smaller to medium-sized projects or for specific needs where scoped styling and simplicity are preferred.
For larger, more complex projects, you might want to explore alternatives like styled-components or emotion, which offer better scalability, flexibility, and performance optimizations for handling large-scale styles.
Add comment