React.js Styling in React
Styling in React.js:
Styling components in React can be accomplished using various techniques, including traditional CSS, Sass, CSS-in-JS libraries like styled-components, or inline styles.
CSS or Sass:
It is not better than any other HTML element styling as it can be done with other CSS or Sass solutions.
It would be the best to include the CSS or scss files either directly or else by importing them into the primary page.
import './styles.css'; // Import CSS file
function MyComponent() {
return (
<div className="container">
<h1 className="title">Hello, World!</h1>
</div>
);
}
CSS file:
/* styles.css */
.container {
max-width: 800px;
margin: 0 auto;
}
.title {
color: blue;
font-size: 24px;
}
CSS-in-JS (e.g., styled-components):
Styled-components is a popular CSS-in-JS library that allows you to write CSS directly inside your JavaScript files using tagged template literals.
import styled from 'styled-components';
const Container = styled.div`
max-width: 800px;
margin: 0 auto;
`;
const Title = styled.h1`
color: blue;
font-size: 24px;
`;
function MyComponent() {
return (
<Container>
<Title>Hello, World!</Title>
</Container>
);
}
Inline styles:
React also supports inline styles, where you pass a JavaScript object containing style properties directly to the 'style' attribute of an element.
function MyComponent() {
const containerStyle = {
maxWidth: '800px',
margin: '0 auto'
};
const titleStyle = {
color: 'blue',
fontSize: '24px'
};
return (
<div style={containerStyle}>
<h1 style={titleStyle}>Hello, World!</h1>
</div>
);
}
Choosing the right approach:
CSS/Sass: a good option for projects that contain hundreds of styles and each style should reside in its own file.
CSS-in-JS: States providing a component-scoped styling and dynamic styling triggered props or the state.
Inline styles: Easy tools to use for simple or single round style but become liable for styling complicated types.