Home > Software engineering >  display result in a div after submitting in React
display result in a div after submitting in React

Time:11-11

i have a calculation function, whenever i put the the numbers in input field i want it to calculate the result when the submit button is clicked and i also want it to show the result in a div. now whenever i hit the button it displays the correct result in console, but i want to know how can i display the final result in a div inside a form with hooks?

the button :

  const handleSubmit = (e) => {
  e.preventDefault();
  console.log(solution)
  }

the form :

     <div onChange={(e) => setResult(solution)}>
      result : {setResult}
     </div>

CodePudding user response:

I assume you have specified your state like this:

const [result, setResult] = useState();

In this case you need to change your handler to update state whenever you get a result:

const handleSubmit = (e) => {
  e.preventDefault();
  //...
  setResult(solution)
  }

and render it in the div:

<div>
    result: {result}
</div>

NOTE: div element doens't have onChange event

CodePudding user response:

<div> doesn't have an onChange. I think what you're trying to do is listen for changes in the solution. The best way to do that is with useState. If you're keeping your solution in state with something like const [result, setResult] = useState(), the div will look more like:

<div>
  result : {result}
</div>

You just need to make sure you're updating the state correctly when the button is pressed. Maybe like:

const handleSubmit = (e) => {
  e.preventDefault();
  //... do calculation and assign it to solution variable
  setResult(solution)
  }
  • Related