9

I'm doing a React coding challenge that requires a value to be updated onKeyUp. I initially set it to update onChange but the tests require onKeyUp so I tried to change it to that, but my fields are no longer updating and I can't type anything into the textarea.

class MarkdownApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };

    this.handleKeyUp = this.handleKeyUp.bind(this);
  }

  handleKeyUp(event) {
    this.setState({ value: event.target.value })
  }

  render() {
    return (
      <form>
        <label>
          Enter your markdown here:
          <br />
          <textarea value={this.state.value} onKeyUp={this.handleKeyUp} id='editor' />
          <br />
        </label>
        <label>
          Your markup will be previewed here:
          <p id='preview'>{marked(this.state.value)}</p>
        </label>
      </form>
    );
  }
}

ReactDOM.render(
  <MarkdownApp />,
  document.getElementById('root')
);

Like I said, this worked fine when it was onChange and my function was handleChange, but since I switched it I can't type anything.

Cdhippen
  • 615
  • 1
  • 10
  • 32

4 Answers4

7

I would just remove the value attribute from the textarea. Because if you put the value attribute to it then the user won't be able to change it interactively. The value will always stay fixed(unless you explicitly change the value in your code). You don't need to control that with React--the DOM will hold onto the value for you.

The only change I've made below is to remove value={this.state.value} from the textarea element:

import React from 'react';
import ReactDOM from 'react-dom';

class MarkdownApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };

    this.handleKeyUp = this.handleKeyUp.bind(this);
  }

  handleKeyUp(event) {
    this.setState({ value: event.target.value })
  }

  render() {
    return (
      <form>
        <label>
          Enter your markdown here:
          <br />
          <textarea value={this.state.value} onKeyUp={this.handleKeyUp} id='editor' />
          <br />
        </label>
        <label>
          Your markup will be previewed here:
          <p id='preview'>{this.state.value}</p>
        </label>
      </form>
    );
  }
}

ReactDOM.render(
  <MarkdownApp />,
  document.getElementById('root')
);
KMA Badshah
  • 895
  • 8
  • 16
duhaime
  • 25,611
  • 17
  • 169
  • 224
2

Since the event happens before the actual value of the textbox is changed, the result of event.target.value is an empty string. Setting the state with the empty string, clears the textbox.

You need to get the pressed key value from the event, and add it to the existing state.value.

Note: I've removed marked from the demo

class MarkdownApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };

    this.handleKeyUp = this.handleKeyUp.bind(this);
  }

  handleKeyUp(event) {
    const keyValue = event.key;
    
    this.setState(({ value }) => ({
      value: value + keyValue
    }))
  }

  render() {
    return (
      <form>
        <label>
          Enter your markdown here:
          <br />
          <textarea value={this.state.value} onKeyUp={this.handleKeyUp} id='editor' />
          <br />
        </label>
        <label>
          Your markup will be previewed here:
          <p id='preview'>{this.state.value}</p>
        </label>
      </form>
    );
  }
}

ReactDOM.render(
  <MarkdownApp />,
  document.getElementById('root')
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • You can identify the press key, and if it's backspace remove the last character. However, you'll have to do it for every special key (arrows, for example), and key combinations. That's why it's a challenge. In the real world, you should use `onChange`. – Ori Drori Jul 12 '18 at 01:42
  • I ran into that yeah. Even though I got onKeyUp to work, the challenge still fails so I'm not sure exactly what's supposed to be happening. I'm gonna create a forum post for them and ask about what's going on – Cdhippen Jul 12 '18 at 01:46
  • You should try the other answers - uncontrolled component, or using ref to update. Might be a better fit for what you need. – Ori Drori Jul 12 '18 at 01:47
  • using ref actually worked better, didn't capture the special characters – Cdhippen Jul 12 '18 at 01:48
  • Or listen to the keyCode of the keyup event and conditionally clear the state based on that keyCode. It really depends what the challenge states exactly... – duhaime Jul 12 '18 at 01:48
  • If you press del, back press it will not work...OnChange function is better in this case. – pixellab Aug 21 '18 at 12:01
1

You could make the textarea uncontrolled by not giving it the value and simply storing the value in state from a ref instead.

Example (CodeSandbox)

class MarkdownApp extends React.Component {
  ref = null;
  state = {
    value: ""
  };

  handleKeyUp = event => {
    this.setState({ value: this.ref.value });
  };

  render() {
    return (
      <form>
        <label>
          Enter your markdown here:
          <br />
          <textarea
            onKeyUp={this.handleKeyUp}
            ref={ref => (this.ref = ref)}
            id="editor"
          />
          <br />
        </label>
        <label>
          Your markup will be previewed here:
          <p id="preview">{marked(this.state.value)}</p>
        </label>
      </form>
    );
  }
}
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • what is the benefit of using ref here? – duhaime Jul 12 '18 at 01:46
  • This works perfectly (although slower than onChange) although the tests still fail so I'll need to message the forums over there to see what's up. I'm also curious, what exactly is ref doing here? – Cdhippen Jul 12 '18 at 01:49
  • @Cdhippen It doesn't seem to be necessary to use the `ref`. Just removing `value={this.state.value}` from the code in your question should work. I did not know the `onKeyUp` event worked like that. – Tholle Jul 12 '18 at 01:50
1

The issue is you have a two way binding with the state = to the value in your textbox. OnChange would update your state after a change is made and the events are done firing. Onkeyup returns the value onkeyup and since you mapped that to your state it will stay as nothing. Remove the value prop and it should work.

William Chou
  • 752
  • 5
  • 16