How to add css in React JS?

Add CSS in React JS:

To add CSS styles to your React.js components, you have a few options. Here's a step-by-step guide with an example:



Step 1: Create a new React component. Let's say you have a component called "MyComponent" that you want to style using CSS.

import React from 'react';

const MyComponent = () => {
  return (
    <div className="my-component">
      <h1>Hello, React!</h1>
    </div>
  );
};

export default MyComponent;

Step 2: Create a CSS file. Create a new CSS file, such as "MyComponent.css", in the same directory as your component.

.my-component {
  background-color: lightblue;
  padding: 20px;
}

.my-component h1 {
  color: red;
}

Step 3: Import the CSS file in your component. In the "MyComponent.js" file, import the CSS file using the import statement.


import React from 'react';
import './MyComponent.css';
// Import the CSS file

const MyComponent = () => {
  return (
    <div className="my-component">
      <h1>Hello, React!</h1>
    </div>
  );
};

export default MyComponent;

Step 4: Style your component using CSS classes. In the JSX code of your component, use the className attribute to apply the CSS classes defined in your CSS file.

import React from 'react';
import './MyComponent.css'; // Import the CSS file

const MyComponent = () => {
  return (
    <div className="my-component">
      <h1 className="title">Hello,
React!</h1>
    </div>
  );
};

export default MyComponent;

Step 5: Apply additional styles to specific elements. You can define CSS rules for specific elements inside your component by using nested selectors in your CSS file.

.my-component {
  background-color: lightblue;
  padding: 20px;
}

.my-component .title {
  color: red;
  font-size: 24px;
}

That's it! Now, when you use the MyComponent component in your application, it will be styled according to the CSS rules defined in the CSS file. Remember to adjust the file paths and class names to match your specific project structure and naming conventions.


In conclusion, we hope you enjoyed reading our post and found it informative and valuable. We put a lot of effort into creating high-quality content and would love to hear your thoughts and feedback. So, please do leave a comment and let us know what you think. Additionally, we invite you to visit our website www.javaoneworld.com to read more beautifully written posts on various topics related to coding, programming, and technology. We are constantly updating our website with fresh and valuable content that will help you improve your skills and knowledge. We are excited to have you as a part of our community, and we look forward to connecting with you and providing you with more informative and valuable content in the future. 

Happy coding!✌✌

No comments:

Post a Comment