How to draw a horizontal line in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# Draw a horizontal line in React

To draw a horizontal line in React:

  1. Use the <hr /> tag and set the style prop on it.
  2. Set the height of the line and optionally set backGroundColor and color.
App.js
export default function App() { return ( <div> {/* ๐Ÿ‘‡๏ธ colored horizontal line */} <hr style={{ background: 'lime', color: 'lime', borderColor: 'lime', height: '3px', }} /> {/* ๐Ÿ‘‡๏ธ colored horizontal line */} <div style={{ background: 'lime', height: '3px', }} /> {/* ๐Ÿ‘‡๏ธ basic horizontal line */} <hr /> {/* ๐Ÿ‘‡๏ธ horizontal line with text */} <div style={{display: 'flex', flexDirection: 'row', alignItems: 'center'}} > <div style={{flex: 1, height: '1px', backgroundColor: 'black'}} /> <div> <p style={{width: '70px', textAlign: 'center'}}>Example</p> </div> <div style={{flex: 1, height: '1px', backgroundColor: 'black'}} /> </div> </div> ); }

react horizontal line

The code for this article is available on GitHub

The code sample shows how to draw horizontal lines in React.

Notice that the <hr /> (horizontal rule) tag is self-closing.

The <hr /> element represents a thematic break between paragraph-level elements.

Like with any other tag, we are able to set a style prop to style the element inline.

App.js
<hr style={{ background: 'lime', color: 'lime', borderColor: 'lime', height: '3px', }} />

Notice that we used two sets of curly braces when passing the style prop to the div element.

The outer set of curly braces marks an expression that is to be evaluated, and the inner set is the object of styles and values.

I've also written an article on how to center a div or a component horizontally & vertically in React.

# Draw a horizontal line with text in the middle

You can also draw a horizontal line with text in the middle.

App.js
<div style={{display: 'flex', flexDirection: 'row', alignItems: 'center'}} > <div style={{flex: 1, height: '1px', backgroundColor: 'black'}} /> <div> <p style={{width: '70px', textAlign: 'center'}}>Example</p> </div> <div style={{flex: 1, height: '1px', backgroundColor: 'black'}} /> </div>
The code for this article is available on GitHub

Make sure to adjust the width of the p element depending on the width of the actual content.

If you need to style the border and border-radius, click on the link and follow the instructions.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev