user11877626
user11877626

Reputation:

How to store values from input field in React?

How to read all the entered input values comma separated. Here i am trying to set html using dangerouslySetInnerHTML. The html contain three input field, how can i read valued entered in all the three input field.

Suppose I entered 24 in first input field then 12 in second input field and 2 in third input field . So now i want to save all the values in state variable comma separated i.e.

24,12,2

import React, { useState } from "react";
import "./styles.css";


const data = {
  htmltag: `<div><p><input type = 'text' /></p><p><input type = 'text' /></p><p><input type = 'text' /></p></div>`
};



export default function App() {

  const [state , setState] = React.useState("")

  const handleChange = () => {
    setState(prev => ({
      ...prev,
      state: 
    }));
    }

  return (
    <>
      <div onChange = {handleChange}
        dangerouslySetInnerHTML={{ __html: data.htmltag }}
      />
      <button> Submit </button>

      <p>values comma separated: {state} </p>
    </>
  );
}

Upvotes: 1

Views: 455

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 186994

I would strongly urge you not to use dangerouslySetInnerHTML. You are basically telling react it's can't manage or reference the elements in there. So you are only left with direct DOM traversal.

But I'm going to assume you have a good reason that isn't apparent from your example.


If you give the parent element an id then you can pull values out with a useEffect hook.

<div
    id="my-inputs"
    onChange={handleChange}
    dangerouslySetInnerHTML={{ __html: data.htmltag }}
/>

Now use an effect to pull data from those ids and put them in state with something like:

useEffect(() => {
  const inputs = Array.from(document.querySelectorAll('#my-inputs input'))
  setState(  
    inputs
      .map(input => input.value)
      .join(',')
  )
})

Upvotes: 1

Related Questions