React Create a Horizontal Divider with Text In between

Joe picture Joe · May 11, 2020 · Viewed 8.4k times · Source

I need to create a React component that is a Horizontal Divider with a content like text In between. All the resources I have online is unable to help me get this done. I tried a material-ui divider by creating a Divider component and placing my text in-between like the example below:

<Divider>Or</Divider>

But I get the error:

hr is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.

I need to achieve this in the image below:

Display a horizontal Divider

Any help will be appreciated.

These are my codes below:

 import React from 'react';
 import { makeStyles } from '@material-ui/core/styles';
 import List from '@material-ui/core/List';
 import Divider from '@material-ui/core/Divider';

 const useStyles = makeStyles((theme) => ({
   root: {
   width: '100%',
   maxWidth: 360,
   backgroundColor: theme.palette.background.paper,
 },
 }));

 export default function ListDividers() {
 const classes = useStyles();

 return (
 <List component="nav" className={classes.root} aria-label="mailbox 
 folders">

  <Divider>Or</Divider>

  </List>
  );
 }

Answer

DiaMaBo picture DiaMaBo · Sep 13, 2020

Using Material UI.

import React from "react";
import { makeStyles } from "@material-ui/core";

const useStyles = makeStyles(theme => ({
  container: {
    display: "flex",
    alignItems: "center"
  },
  border: {
    borderBottom: "2px solid lightgray",
    width: "100%"
  },
  content: {
    paddingTop: theme.spacing(0.5),
    paddingBottom: theme.spacing(0.5),
    paddingRight: theme.spacing(2),
    paddingLeft: theme.spacing(2),
    fontWeight: 500,
    fontSize: 22,
    color: "lightgray"
  }
}));

const DividerWithText = ({ children }) => {
 const classes = useStyles();
 return (
  <div className={classes.container}>
    <div className={classes.border} />
    <span className={classes.content}>{children}</span>
    <div className={classes.border} />
  </div>
 );
};
export default DividerWithText;

You can import and use it like the below

<DividerWithText>Or</DividerWithText>

Result material ui divider with text at center