首页 > 解决方案 > How To Create Dynamic Input box with label and Render Input value in ReactJs

问题描述

how to create Dynamic label And Input in On Click . Such As If I type label as Country Then user can input country name in input Box. and on submit And all the input value should populate with their label name , such as

Codesandbox Link: Dynamic form

example:

import React, { useState } from "react";
import ReactDOM from "react-dom";
import { ConProvider } from "../ContextApi";
import Data from "./Component/Data/Data";
import InputBox from "./InputBox";

import "./styles.css";

function App() {
  const [input, setinput] = useState(["input-0"]);
  const appendInput = (e) => {
    // e.preventDefault();
    var newInput = `input-${input.length}`;
    setinput(input.concat([newInput]));
  };
  const handleInput = (i) => (e) => {
    let inputs = [...input];
    inputs[i] = e.target.value;
    setinput(inputs);
  };
  console.log(input);
  return (
    <div className="App">
      <Data />
      <form>
        {input.map((i, index) => (
          <InputBox key={i} handleInput={handleInput} indexProps={index} />
        ))}
      </form>

      {input.map((i) => {
        return <p key={i}>{i}</p>;
      })}
      <button onClick={appendInput}>Add Input</button>
    </div>
  );
}

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

标签: reactjs

解决方案


推荐阅读