Yige Song
Yige Song

Reputation: 373

ReactJs: Listen to event in "span" tag ES6

I have a class-based component, having the below codes within it:

state = {value: "Hello", input: null}

inputChangeHandler = (event) => {
    this.setState({input: event.target.value});
} 

changeValueHandler = () => {
    this.setState({value: this.state.input})
}

render(){
    <div>
        <h1>{this.state.value}</h1>
        <input type="text" onChange={this.inputChangeHandler} />
        <button onClick={(event) => this.inputChangeHandler(event)}>Save input</button>
    </div>
}

This works: When I type "World" in the input box then press save. The title changes from "Hello" to "World".

However, I want to have an expandable input box to support longer input paragraphs. So I replace the <input> tag with <span>:

<span type="text" role="textbox" onChange={this.inputChangeHandler} contentEditable={true} />

This doesn't work: When I type "World" in the span box then press save. The title is still the default "Hello", even though I intend to change it to "World".

Thank you for helping!

Upvotes: 0

Views: 2486

Answers (1)

Maniraj Murugan
Maniraj Murugan

Reputation: 9084

You need to change,

<span type="text" role="textbox" onChange={this.inputChangeHandler} contentEditable={true} />

To:

<span contentEditable="true" onInput={this.inputChangeHandler}>
  Some text{" "}
</span>

So in contentEditable you have to use onInput to capture the change event.

Then modify inputChangeHandler like,

  inputChangeHandler = (event) => {
    this.setState({ input: event.currentTarget.textContent });
  };

Here we need to take event.currentTarget.textContent that has the change in text user type.

Edit React basic class component (forked)

Upvotes: 4

Related Questions