When it comes to styling in JSX, the style property functions similarly to HTML's style attribute. Both of these accept only CSS properties, excluding selectors, pseudo-elements, or pseudo-classes.
Utilizing the Style Property
To improve readability and maintain clear separation of styles, consider the following approach:
const h2Style = {
fontSize: '20px';
color: 'black';
}
const spanStyle = {
color: 'white';
}
const Main = () => {
return (
<h2 style={h2Style}>Hello<span style={spanStyle}>Test</span></h2>
);
}
Alternatively, for a more organized structure:
const styles = {
h2: {
fontSize: '20px';
color: 'black';
},
span: {
color: 'white';
}
}
const Main = () => {
return (
<h2 style={styles.h2}>Hello<span style={styles.span}>Test</span></h2>
);
}
If you prefer defining styles externally, consider using CSS/SCSS:
import "./your-css.css";
const Main = () => {
return (
<h2 className="title">Hello<span>Test</span></h2>
);
}
Where .your-css.css
would contain:
.title {
fontSize: '20px';
color: 'black';
}
.title span {
color: 'white';
}
For a more sophisticated approach using CSS-in-JS with styled-components:
import React from 'react';
import styled from 'styled-components';
const Title = styled.h2`
fontSize: '20px';
color: 'black';
span {
color: 'white';
}
`;
const Main = () => {
return (
<Title>Hello<span>Test</span></Title>
);
}
export default Main;