How To Style The Border CSS Property In React

Style the border CSS property in React

In this article, we will go through how to style the border CSS property in React, for example, using inline Style or Style in the CSS file. Let’s read it now.

Style the border CSS property in React

An element’s border can be set using CSS Border or the CSS border property.

An element’s border style, color, and size can all be set with the CSS border properties. The following are the CSS border properties:

  • border-style
  • border-color
  • border-width
  • border-radius

Use inline Style and useState hook method

We will use the useState() hook to change the Style of the border as we need, and that state will be set in the style attribute of the element we need to change the border property. Check out the code below to learn more about it.

Code:

import { useState } from "react";

export default function App() {
  const [borderStyle, setBorderStyle] = useState({
    width: "100px",
    height: "100px",
    border: "3px solid red",
  });
  return (
    <div>
      <h2>Style the border CSS property in React | LearnShareIT</h2>
      <div style={borderStyle}></div>
      <br />
      <button
        onClick={() =>
          setBorderStyle({
            width: "100px",
            height: "100px",
            border: "3px solid blue",
          })
        }
      >
        Change border style
      </button>
    </div>
  );
}

Output:

Using inline Style, we can set the style value for the border of the div tag, and when we click the change style button, the red border will change to blue. Or you can refer to the method below.

Style in CSS file method

The external format is built and stored on a separate file with a .css extension. This file can have only tags containing the defined style formats. Note that no HTML elements other than the tag pair can be used in this file.

In this way, you will have to create a CSS file to style the border of the div tag we need to style. See the JS and CSS code files below.

Code:

.border__div {
    width: 100px;
    height: 100px;
    border: 5px solid blue;
}
.border__div:hover {
    border: 5px dashed green;
}
import "./App.css";

export default function App() {
  return (
    <div>
      <h2>Style the border CSS property in React | LearnShareIT</h2>
      <div className="border__div"></div>
    </div>
  );
}

Output:

So you can style the border CSS property in React this way. It will change from blue to green when you hover on a div tag with class border__div. Hope these methods are helpful to you.

Summary

To summarize, there are many ways to style the border CSS property in React. After reading this article, we already know two ways to do this, but I recommend the method: Using inline style and useState hook method to change user behavior by state quickly.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *