AsiaArgento1
AsiaArgento1

Reputation: 3

How to manage state on a single react element for hover effect?

I'm trying to setup a simple 'icon to text' hover effect for my portfolio website in React. When I set it up it changes ALL of the icons on hover, I just want to change the one icon at a time.

export default class Home extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isHover: false
    };

    this.onMouseEnterHandler = this.onMouseEnterHandler.bind(this);
    this.onMouseLeaveHandler = this.onMouseLeaveHandler.bind(this);
  }

  onMouseEnterHandler() {
    this.setState({
      isHover: true
    });
  }

  onMouseLeaveHandler() {
    this.setState({
      isHover: false
    });
  }

  render() {
    return (
      <div className="home">
      <div className="hamburger-icon"></div>
        <section className="info-section">
          <div className="logo">M</div>
          <div className="info-box-top">
            <a onMouseEnter={this.onMouseEnterHandler} onMouseLeave={this.onMouseLeaveHandler} className="home active" id="one" href="/">
              { this.state.isHover
                  ? <span>Home</span>
                  : <FontAwesomeIcon icon={faHome} />
              }
            </a>
            <a id="two" href="/about"><FontAwesomeIcon icon={faUser} /></a>
            <a id="three" href="/skills"><FontAwesomeIcon icon={faCog} /></a>
            <a id="four" href="/gallery"><FontAwesomeIcon icon={faEye} /></a>
            <a id="five" href="/contact"><FontAwesomeIcon icon={faEnvelope} /></a>
          </div>

Upvotes: 0

Views: 1103

Answers (2)

Vipin Yadav
Vipin Yadav

Reputation: 1113

You can manage it through css only but if you want this to manage form javascript than you can manage state of each individual element. please check my codesandbox link for your refrence. https://codesandbox.io/s/react-example-1nyfs

Upvotes: 1

akhtarvahid
akhtarvahid

Reputation: 9769

Optimized code

let arr = [
  { id: "one", href: "/", icon: faHome, name: "Home" },
  { id: "two", href: "/about", icon: faUser, name: "About" },
  { id: "three", href: "/skills", icon: faCog, name: "Skills" },
  { id: "four", href: "/gallery", icon: faEye, name: "Gallary" },
  { id: "five", href: "/contact", icon: faEnvelope, name: "Contact" }
];
class App extends React.Component {
  state = {
    isHover: false
  };

  onMouseEnterHandler = selected => {
    console.log(selected);
    this.setState({
      isHover: selected
    });
  };

  render() {
    return (
      <div className="info-box-top">
        {arr.map(a => (
          <a key={a.id}
            onMouseEnter={() => this.onMouseEnterHandler(a)}
            id={a.id}
            href={a.href}
          >
            {this.state.isHover.id === a.id ? (
              <span>{a.name}</span>
            ) : (
              <FontAwesomeIcon icon={a.icon} />
            )}
          </a>
        ))}
      </div>
    );
  }
}

Live demo

Upvotes: 0

Related Questions