Inline Styling on React
Inline styles in React allow us to apply styles to individual elements in a more flexible way than traditional CSS. Today we are gonna learn how we can achieve this in react.
- Creating our React component
- Define a style object
- Apply the style object to the element
- Use variables in the style object
- Use conditional styles
At first let's create a new React component, or use an existing one, that we want to apply inline styles to. For example:
import React from 'react';
function MyComponent() {
return <div>Hello World</div>;
}
export default MyComponent;
We just created a new Component name MyComponent.
We will now create a javaScript object styles
that defines the styles we want to apply to the element.
const styles = {
backgroundColor: 'red',
color: 'white',
padding: '10px',
};
Now, we will use the style
attribute on the element and pass out styles
objects
import React from 'react';
const styles = {
backgroundColor: 'red',
color: 'white',
padding: '10px',
};
function MyComponent() {
return <div style={styles}>Hello World</div>;
}
export default MyComponent;
We can also use variables in the style object to make our code more dynamic.
import React from 'react';
const primaryColor = 'red';
const textColor = 'white';
const styles = {
backgroundColor: primaryColor,
color: textColor,
padding: '10px',
};
function MyComponent() {
return <div style={styles}>Hello World</div>;
}
export default MyComponent;
To apply styles conditionally we can follow this snippet -
import React from 'react';
const primaryColor = 'red';
const secondaryColor = 'blue';
const textColor = 'white';
function MyComponent({ isPrimary }) {
const styles = {
backgroundColor: isPrimary ? primaryColor : secondaryColor,
color: textColor,
padding: '10px',
};
return <div style={styles}>Hello World</div>;
}
export default MyComponent;
In this example, the isPrimary prop determines whether the backgroundColor should be primaryColor
or secondaryColor
.
And that's it! We can use inline styles in your React components by following these mentioned procedures.