olo
olo

Reputation: 5271

onMouseOver and onMouseOut to toggle input and div, and change value of the div

I am new to react. What I am trying to achieve is shown below, when I hover the value, value changes to an input and enables to change the value in the input field. It is easy for me to write pure javascript, but I'd like to achieve it in reactjs and want to learn it.

The idea is that, hide the value span tag and replace it with an input with the value when onhover it.

I'd like to know how to toggle <span className="value"> and <input type="text" /> when onMouseOver and onMouseOut

enter image description here

import React, { Component } from "react";

class ChangeValue extends Component {
  state = {
    text: ""
  };

  onMouseOver = e => {
    // what should be here? 
  };

  onMouseOut = e => {
    this.setState({
      text: ""
    });
  };

  render() {
    const { text } = this.state;
    return (
      <div className="inputsValue">
        <span className="property">Name</span> :{" "}
        <span className="value">Value</span>
        <input type="text" />
      </div>
    );
  }
}

export default ChangeValue;

Upvotes: 1

Views: 1489

Answers (1)

Kiran Shinde
Kiran Shinde

Reputation: 5992

You can do something like this

import React, { Component } from "react";

class ChangeValue extends Component {
  state = {
    text: "",
    isEditable: false
  };

  onMouseOver = e => {

    this.setState({
       isEditable: true,
       text: e.target.value
    })
  };

  onMouseOut = e => {
    this.setState({
      isEditable: false
    });
  };

  render() {
    const { text } = this.state;
    return (
      <div className="inputsValue">
        { this.state.isEditable ?
             <input type="text" value={this.state.text} onMouseOut={(e) => this.onMouseOut(e)}/>
          :
             <div>
               <span className="property">Name</span> :{" "}
               <span className="value" onMouseOver={(e) => this.onMouseOver(e)}>{this.state.text}</span>
             </div>
      </div>
    );
  }
}

export default ChangeValue;

Upvotes: 1

Related Questions