CSS-in-JS libraries in React.js allow you to write and manage styles directly in your JavaScript or TypeScript code. This can offer benefits like scoped styles, dynamic theming, and better integration with your components. Some popular CSS-in-JS libraries include styled-components, emotion, and JSS. Below, I'll provide a basic example using styled-components:
Install the Library:
You need to install the CSS-in-JS library of your choice. In this example, we'll use styled-components
.
bashnpm install styled-components
Create a Styled Component:
Import the library and use it to create a styled component. Below is a simple example:
jsx// Import the styled function from the library
import styled from 'styled-components';
// Create a styled component
const StyledButton = styled.button`
background-color: #4caf50;
color: white;
padding: 10px 20px;
font-size: 16px;
border: none;
border-radius: 4px;
cursor: pointer;
&:hover {
background-color: #45a049;
}
`;
Use the Styled Component in Your React Component:
jsximport React from 'react';
const MyComponent = () => {
return (
<div>
<h1>Hello, this is my component</h1>
{/* Use the styled component */}
<StyledButton>Click me</StyledButton>
</div>
);
};
export default MyComponent;
Dynamic Styles:
CSS-in-JS libraries often allow you to use JavaScript expressions for dynamic styling. For example, in styled-components
, you can use props to conditionally apply styles:
jsxconst StyledButton = styled.button`
background-color: ${props => (props.primary ? '#4caf50' : '#008CBA')};
color: white;
padding: 10px 20px;
font-size: 16px;
border: none;
border-radius: 4px;
cursor: pointer;
&:hover {
background-color: ${props => (props.primary ? '#45a049' : '#0056b3')};
}
`;
And then use it like this:
jsx<StyledButton primary>Primary Button</StyledButton>
<StyledButton>Secondary Button</StyledButton>
Remember to check the documentation of the specific library you're using for more advanced features and configuration options. The process is similar for other CSS-in-JS libraries like Emotion or JSS. Choose the one that fits your project and coding style the best.