Realize the effect of underline following in navigation bar by react

Time:2021-5-29

design sketch:
Realize the effect of underline following in navigation bar by react

App.jsx

import React, { Component } from 'react'
import style from './index.module.less'
export default class App extends Component {

  state = { width: 0, left: 0}

  enter = (event) => {
    const {clientWidth, offsetLeft } = event.target
    this.setState({ 
      width: clientWidth,
      left: offsetLeft
    })
  }

  leave = () => {
    this.setState(() =>({ width: 0 }) )
  }
  render () {
    const { width, left } = this.state
    return (
      <>
        <div className={ style.header }>
          <ul ref="ul" onMouseLeave={ this.leave } >
            < Li onmouseenter = {this. Enter} > Home Page</li>
            < Li onmouseenter = {this. Enter} > navigation one</li>
            < Li onmouseenter = {this. Enter} > navigation 2</li>
            < Li onmouseenter = {this. Enter} > navigation 3</li>
            < Li onmouseenter = {this. Enter} > navigation 4</li>
          </ul>
          <div className={style.line} style={{width: width, left: left, height: '2px'}}></div>
        </div>
      </>
    )
  }
}

App.module.less

.header {
  position: relative;
  padding-left: 50px;
  ul {
    display: flex;
    margin: 0;
    padding: 0;
    li {
      list-style: none;
      padding: 10px;
      cursor: pointer;
      font-weight: 500;
      &:hover{
        color: orangered
      }
    }
  }
  .line {
    position: absolute;
    bottom: 0;
    transition: .3s cubic-bezier(.4,0,.2,1);
    background-color: #c7000b;
  }
}