Inline Style in React
In HTML:
<div style="color: blue; background-color: red;">
This is a div with inline styles.
</div>
In React:
<div style={{ color: 'red', backgroundColor: 'green' }}>
React JS Style
</div>
Notes:
- Style is passed as a JavaScript object inside JSX.
- CSS properties must be written in camelCase.
- Use commas, not semicolons, after each property.
How is React inline style different from regular HTML style?
- In HTML: style is a string (
"color: red;"
) - In React: style is an object (
{ color: 'red' }
) - Property names use camelCase instead of kebab-case.
- Values are in quotes if they are strings.
Example: User Profile Card with Inline Style
function App() {
return (
<div>
<h1 style={{ color: "red" }}>Inline Style in React</h1>
<div
style={{
border: "1px solid #ccc",
width: "200px",
boxShadow: "1px 2px 3px 0px #cccccc57",
margin: "10px",
}}
>
<img
style={{ width: "200px" }}
src="https://www.w3schools.com/howto/img_avatar.png"
alt=""
/>
<div style={{ padding: "5px" }}>
<h4>Anil Sidhu</h4>
<p>Software Developer</p>
</div>
</div>
</div>
);
}
Make It Reusable with a JS Style Object
const cardStyle = {
border: "1px solid #ccc",
width: "200px",
boxShadow: "1px 2px 3px 0px #cccccc57",
margin: "10px",
};
const imageStyle = {
width: "200px",
};
const textContainerStyle = {
padding: "5px",
};
Use it in JSX:
<div style={cardStyle}>
<img style={imageStyle} src="..." alt="" />
<div style={textContainerStyle}>
<h4>Anil Sidhu</h4>
<p>Software Developer</p>
</div>
</div>
Create Multiple Cards in the Same Row
<div style={{ display: "flex", flexWrap: "wrap" }}>
<div style={cardStyle}>
<img style={imageStyle} src="..." alt="" />
<div style={textContainerStyle}>
<h4>Anil Sidhu</h4>
<p>Software Developer</p>
</div>
</div>
<div style={cardStyle}>
<img style={imageStyle} src="..." alt="" />
<div style={textContainerStyle}>
<h4>Anil Sidhu</h4>
<p>Software Developer</p>
</div>
</div>
</div>
display: "flex"
helps to align cards side by side in the same row.