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.

Table of Contents

  1. Creating our React component
  2.  Define a style object
  3. Apply the style object to the element
  4. Use variables in the style object
  5. Use conditional styles

Creating our React component

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.

Define a style object

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',
};

Apply the style object to the element

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;

Use variables in the style object

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;

Use conditional styles

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.