Inserting data into the style attribute from a separate file in React

We can avoid writing style objects in the component file, as in the previous lesson, and create a separate file with our style objects and import them into the required component.

So, let's take our component without CSS styles:

App.jsfunction App() {
  return (
    <div>
      <p>text</p>
      <p>text</p>
      <p>text</p>
    </div>
  );
}

Let's create a separate file styles.js in the src folder, in which we will write our objects with styles:

styles.jsconst class1 = {
  width: '200px',
  border: '2px solid brown',
  padding: '10px',
  textAlign: 'center',
};

const class2 = {
  color: 'orangered',
  fontWeight: 'bold',
};

const class3 = {
  fontStyle: 'italic',
  color: 'brown',
};

const class4 = {
  backgroundColor: 'orange',
  fontWeight: 'bold',
  color: 'white',
};

Let's not forget to export our objects as one object styles at the bottom of the styles.js file:

styles.jsexport const styles = {
  class1: class1,
  class2: class2,
  class3: class3,
  class4: class4
};

Now we import the styles object into our component:

App.jsimport { styles } from "./styles";       

Now we can apply the CSS style object we need from the general styles object to our tags. Let's apply the styles from the class2 object to the first paragraph:

App.js<p style={styles.class2}>text</p>

In a similar way, we will add styles from objects to the remaining tags.

As a result, the component code will look like this:

App.jsfunction App() {
  return (
    <div style={styles.class1}>
      <p style={styles.class2}>text</p>
      <p style={styles.class3}>text</p>
      <p style={styles.class4}>text</p>
    </div>
  );
}  
Задание 1

Take the React component you made in the task for the last lesson. Create a separate file styles.js that will contain CSS style objects for your tags, export them as a single object, apply the styles to your React component.