0

I want my handleChange function to change the value of input to subscript. What is the way to do this in React?

class App extends Component {
  state = {
    equation: ""
  };

  handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  render() {
    const { equation } = this.state;
    console.log(equation);
    return (
      <div>
        <input onChange={this.handleChange} value={equation} name="equation" />
      </div>
    );
  }
}
kenodek
  • 362
  • 1
  • 2
  • 13
  • 1
    @ZohirSalak read up a little, they're doing destructuring at the top of the render method so that you don't have to type `this.state` for every reference to `equation`. Also, the `handleChange` method is fine, it's using a computed property so that it becomes a reusable method instead of hardcoded names. Now they can add 100 different (or more/less) inputs and use the same method to handle it – Sterling Archer Apr 24 '19 at 18:24
  • You'll have to find or write a method that converts letters into subscript html entities (a simple map should suffice). As it stands, the `sub` and `sup` methods (that return the string wrapped in the respected tags) are deprecated and I can't seem to find a modern standard for this – Sterling Archer Apr 24 '19 at 18:26
  • Excuse me I was misinformed. The String methods `.sub` and `.sup` are deprecated, not the HTML tags. So just use the tags and you'll be good to go (if an input can render it) – Sterling Archer Apr 24 '19 at 18:30
  • I was trying to use sub tags within input and it doesn't seem to work. The idea with function seems to be better – kenodek Apr 24 '19 at 18:33
  • It looks like it's the only way to "render" html inside an input tag (https://stackoverflow.com/questions/5823835/html-in-the-input-field-value), so the sub tag might not help here, it does sound like you need the subscript letter entities instead – Sterling Archer Apr 24 '19 at 18:36
  • Actually I need only digits to be subscript and it looks like there are only superscript entities :) – kenodek Apr 24 '19 at 18:40

1 Answers1

2

Regex select + capture digit characters, and replace with respective subscript html entity:

  handleChange = event => {
    const formattedValue = event.target.value.replace(/(\d)/g, '&#832$1;');
    this.setState({ [event.target.name]: formattedValue });
  };
Drazen Bjelovuk
  • 5,201
  • 5
  • 37
  • 64