Style the border CSS property in React

avatar

Borislav Hadzhiev

Tue Apr 26 20222 min read

Style the border CSS property in React #

Use the border css property to set the border style of an element in React, e.g. <div style={{border: '1px solid rgba(0,255,0,0.3)'}}>. If you only need to style a specific border, use the corresponding property, e.g. borderBottom.

App.js
const App = () => { return ( <div> <div style={{border: '1px solid red'}}>Some content here</div> <br /> <div style={{border: '1px dashed red'}}>Some content here</div> <br /> <div style={{border: '1px solid rgba(0,255,0,0.3)'}}> Some content here </div> <br /> <div style={{border: '2px dotted red'}}>Some content here</div> <br /> <div style={{borderBottom: '2px dotted red'}}>Some content here</div> <br /> <br /> <div style={{borderTop: '2px dotted red'}}>Some content here</div> </div> ); }; export default App;

The examples show how to style the border CSS property of an element in React.

Note that you have to wrap the value of the border property in a string.

App.js
<div style={{border: '1px solid rgba(0,255,0,0.3)'}}> Some content here </div>

If you only need to style a specific border, e.g. border-bottom, use camelCased property names - borderBottom.

App.js
<div style={{borderBottom: '2px dotted red'}}>Some content here</div>

Multi-word property names are camelCased in the object we pass to the style prop in React.

Alternatively, you can write your styles in a file with a .css extension.

App.css
.red-border { border: 1px solid red; }

And here is how we would import and use the red-border class.

App.js
// 👇️ import css file import './App.css'; const App = () => { return ( <div> <div className="red-border">Hello world</div> </div> ); }; export default App;
When importing global CSS files in React, it's a best practice to import the CSS file into your index.js file.

The index.js file is the entry point of your React application, so it's always going to be ran.

On the other hand, if you import a CSS file into a component, the CSS styles might get removed once your component unmounts.

Use the search field on my Home Page to filter through my more than 1,000 articles.