Charles Jr.
Charles Jr.

Reputation: 127

updated react form using controlled state

I have to read an endpoint and bind the values onto a form, but I'm struggling with binding the value of the array into the tag

function App() {
  const data = [
    {
      f_name: "alicia"
    },
    {
      l_name: "johnson"
    }
  ];

  function handleChange(e) {
    console.log("e", e.target.value);
  }

  return (
    <div className="App">
      {data.map(o => (
        <input name={o} onChange={handleChange} type="text" />
      ))}
    </div>
  );
}

https://codesandbox.io/s/cocky-ives-cx5nx

How do I bind the f_name and l_name property to the name attr?

Upvotes: 0

Views: 46

Answers (3)

thortsx
thortsx

Reputation: 2280

With my options, I will use regex:

import React from "react";
import ReactDOM from "react-dom";

function App() {
  const data = [
    {
      f_name: "alicia"
    },
    {
      l_name: "johnson"
    }
  ];

  function handleChange(e) {
    console.log("e", e.target.value);
  }

  return (
    <div className="App">
      {data.map(o => {
        for(let key of Object.keys(o)) {
          let name = /([a-zA-Z]+_name)/g.test(key) ? o[key] : ''
          return <input name={name} onChange={handleChange} type="text"/>
        }
      })}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Upvotes: 0

Nithin Thampi
Nithin Thampi

Reputation: 3679

I suggest, Build a state out of the data and then make it a controlled component. Try something like below

import React, {useState} from "react";
import ReactDOM from "react-dom";

function App() {
  const data = [
    {
      f_name: "alicia"
    },
    {
      l_name: "johnson"
    }
  ];

  const [state, setState] =  useState(data.reduce((acc, val) => {
    acc = {...acc, ...val}
    return acc;
  }, {}));
  console.log(state);

  function handleChange(e, key) {
    setState({...state, [key]: e.target.value });
  }

  return (
    <div className="App">
      {Object.keys(state).map((key) => (
        <input
        key={key}
        name={key}
        value={state[key]}
        onChange={(e) => {
            handleChange(e,key);
          }
        }
          type="text"
        />
      ))}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
    <App />, rootElement
);

Upvotes: 1

Md. Easin
Md. Easin

Reputation: 51

Here is the simple way to add name attr by f_name and l_name ..

https://codesandbox.io/embed/flamboyant-cherry-tvq7s

enter image description here

Upvotes: 0

Related Questions