React JS Tutorial: CSS Stylesheets šŸŽÆ

beginner
6 min

React JS Tutorial: CSS Stylesheets šŸŽÆ

Welcome back to CodeYourCraft! Today, we're diving into the world of CSS Stylesheets in React JS. By the end of this lesson, you'll have a solid understanding of how to style your React components.

Why CSS in React? šŸ’”

In a React application, you can style your components using JavaScript, CSS, or a CSS-in-JS library like Styled Components or Emotion. Today, we'll focus on using external CSS files, as it's a great way to organize and reuse styles across your application.

Setting up CSS šŸ“

To link an external CSS file in your React project, follow these steps:

  1. Create a new CSS file in the src/styles folder. Let's call it App.css.
  2. Inside the src folder, create a new folder called public.
  3. Inside the public folder, create a new folder called css.
  4. Move your CSS file (App.css) into the public/css folder.
  5. In your src folder, open the index.js file and import your CSS file at the top:
javascript
import React from 'react'; import ReactDOM from 'react-dom'; import './styles/App.css'; // <-- Import your CSS file here! // ... rest of your code

Styling a Component šŸŽØ

Now let's style a simple React component using our external CSS file:

  1. First, create a new component called Title:
javascript
import React from 'react'; const Title = () => { return ( <h1>Welcome to CodeYourCraft</h1> ); }; export default Title;
  1. In your App.css file, add the following styles:
css
h1 { font-family: Arial, sans-serif; color: #333; text-align: center; }
  1. Update your App component to use the Title component:
javascript
import React from 'react'; import ReactDOM from 'react-dom'; import Title from './Title'; // <-- Import your new component here! import './styles/App.css'; // <-- Import your CSS file here! const App = () => { return ( <div> <Title /> </div> ); }; export default App;
  1. Run your application and see the magic! šŸŽ‰

Pro Tip šŸ’”

šŸ“ Remember, for components within components, use the className prop instead of the class prop.

Quiz Time šŸŽ²

Quick Quiz
Question 1 of 1

What should you use instead of the `class` prop when styling a child component in React?

That's it for today! In the next lesson, we'll dive deeper into CSS Stylesheets in React, exploring advanced techniques and practical examples. See you then! šŸ˜„

Happy coding! šŸ¤–šŸ’»šŸŒŸ