sleatrou
sleatrou

Reputation: 341

How can I draw red horizontal line in React

How can I draw a horizontal line (hr) in a react component using dynamic color?

Here's what I have so far:

render {
    let color = 'red';
    return (
        <div> 
            There is a red HR
           <hr />
        <div>
    )
}

Upvotes: 31

Views: 162277

Answers (4)

Anjan Talatam
Anjan Talatam

Reputation: 3996

Update

Below is the code for a simple Horizontal line styled with CSS.

.separator {
  height: 10px;
  background-color: red;
  border: none;
}
<hr class="separator" />

Key points I noticed after working with the <hr /> tag

  1. Passing color from styles has no effect on <hr />. Use background-color to change hr color with styles.
  2. background-color works only if height is mentioned
  3. border: none is recommended as hr comes with a default border of 1px

React Component

function Separator({ color = "black", height = 1 }) {
  return (
    <hr
      style={{
        backgroundColor: color,
        height: height,
        border: "none"
      }}
    />
  );
}

<Separator color="red" height="10px" />

Key points

  1. I recommend using external styles over inline styles ( unless it's tailwindcss )
  2. You need to default color to black and height to 1. These are the default <hr /> styles excluding border and if not defaulted you won't see a horizontal line if one of color, height is missing

MDN Docs

Edit sof-answer-hr-line

Upvotes: 1

Aman Saxena
Aman Saxena

Reputation: 51

Here is a simple way to create a horizontal line in your react js app

    <div style={{ borderTop: "2px solid #fff ", marginLeft: 20, marginRight: 20 }}></div>

Upvotes: 5

Jojo Joseph
Jojo Joseph

Reputation: 1633

<hr  style={{
    color: '#000000',
    backgroundColor: '#000000',
    height: .5,
    borderColor : '#000000'
}}/>

Only adding the borderColor, to change the exact full-color change of <hr /> tag

Upvotes: 9

Luke Willis
Luke Willis

Reputation: 8580

One way to set up the component:

const ColoredLine = ({ color }) => (
    <hr
        style={{
            color: color,
            backgroundColor: color,
            height: 5
        }}
    />
);

And then use it with:

<ColoredLine color="red" />

For a full breakdown on how to style <hr />, see http://www.sovavsiti.cz/css/hr.html

Upvotes: 59

Related Questions