Styling Components

Styling Components

In this tutorial, we will learn how to style React components using CSS.

Creating a Button Component

First, let's create a simple Button component that we will style using CSS. Create a new file named Button.jsx and paste the following code:

import React from "react";
import "./Button.css";

const Button = ({ text }) => {
  return <button className="button">{text}</button>;
};

export default Button;

This component accepts a text prop and returns a button element with the class button. Notice that we are importing a CSS file named Button.css.

Styling the Button Component

Open the Button.css file and add the following styles:

.button {
  background-color: #4caf50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

These styles will give our button a green background color and white text.

Using the Button Component

Now that we have created and styled our Button component, let's use it in our App component. Open the App.jsx file and update the code to the following:

import React from "react";
import Button from "./Button";

const App = () => {
  return (
    <div>
      <h1>Styling Components</h1>
      <Button text="Click me!" />
    </div>
  );
};

export default App;

Notice that we are importing the Button component and using it with a text prop.

Conclusion

In this tutorial, we learned how to style React components using CSS. By separating the styling from the component logic, we can create reusable and customizable components that can be used throughout our application.

Try changing the styles in the Button.css file to see the effect on the button.