1

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>
    </>
  );
}

3
  • Does data come from an external source? Do you control what HTML is in there? Commented Jun 30, 2020 at 17:56
  • Yes i can have a bit of HTML control Commented Jun 30, 2020 at 17:57
  • Can you add a name property to each input field? Commented Jun 30, 2020 at 18:08

1 Answer 1

1

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(',')
  )
})
Sign up to request clarification or add additional context in comments.

5 Comments

is there any other way like using useRef and then using querySelector get all the input values, as i am beginner in React and learning
Before I answer that are you sure you want to be using dangerouslySetInnerHTML? Because this is easier without that. See the official docs on form handling
Actually i am getting this HTML from API so i have to use dangerouslySetInnerHTML
So possibly will not be able to modify in HTML part, so is there any other approach ? If you come across any of such idea please do tell.
See my update. Basically, you add an id to the container HTML that you can control, and then use DOM methods to get values out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.