Home > OS >  Why is eval not working in react? How to fix?
Why is eval not working in react? How to fix?

Time:11-11

I am trying to make a calculator using react,and I am not able to use 'eval' in the input field. this following code gives this error-

import React, { Component } from "react";

class myApp extends React.Component {
  state = {
    equation: "",
  };

  handleClick = (e) => {
    this.setState({ equation: e.target.value });
    console.log(eval(this.state.equation));
  };
  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.equation}
          onChange={this.handleClick}
        ></input>
        <h1>{this.state.equation}</h1>
        <button onClick>enter</button>
      </div>
    );
  }
}

export default myApp;

Error-

SyntaxError: Unexpected end of input

Why does this error occur and how can I fix this ?

CodePudding user response:

setState inside event handlers is asynchronous - this mean it will update this.state after event handler finishes (this allows react to batch multiple setStates calls into one update).

In your case you are calling eval with previous state value - "" (and this gives an error).

Instead of using this.state.equation try:

console.log(eval(e.target.value));

CodePudding user response:

You need to first set the value after putting in eval() method. eval('10 10') working fine but when value is eval('10 ') is throw the error in javaScript as well.

In react after set value you can convert or try vie eval().

If you enter value its should be output like below :

1
10
10 
10 2
10 20

So when value is 10 its throw the error.

You can read more about eval

You can try this way.

const { useState, useEffect } = React;

const App = () => {
  const [state, setState] = useState({ equation: "" });

  useEffect(() => {}, [state.equation]);

  const handleChange = (e) => {
    const value = e.target.value;
    console.log(value);
    setState({ equation: value });
  };

  const handleOnClick = (e) => {
    console.log(eval(state.equation));
    setState({ equation: eval(state.equation) });
  };

  return (
    <div>
      <input type="text" value={state.equation} onChange={handleChange} />
      <h1>{state.equation}</h1>
      <button onClick={handleOnClick}>enter</button>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related