1

I am new in React and I am confused, What I want is i have a drop down list with options as 1,2,3,4.... upto n. Suppose if I select on dropdown number 5 then dynamically 5 input fields should get generated. Also for each input field which is created. I should be manually able to remove them with a remove button.

I have created adding of input options but it is manual like we click on add button new option is added and when we click remove that particular option with index gets deleted. You can refer this link for code

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        users: [{firstName: "", lastName: ""}]
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  
  addClick(){
    this.setState(prevState => ({ 
        users: [...prevState.users, { firstName: "", lastName: "" }]
    }))
  }
  
  createUI(){
     return this.state.users.map((el, i) => (
       <div key={i}>
            <input placeholder="First Name" name="firstName" value={el.firstName ||''} onChange={this.handleChange.bind(this, i)} />
          <input placeholder="Last Name" name="lastName" value={el.lastName ||''} onChange={this.handleChange.bind(this, i)} />
            <input type='button' value='remove' onClick={this.removeClick.bind(this, i)}/>
       </div>          
     ))
  }
  
  handleChange(i, e) {
     const { name, value } = e.target;
     let users = [...this.state.users];
     users[i] = {...users[i], [name]: value};
     this.setState({ users });
  }
  
  removeClick(i){
     let users = [...this.state.users];
     users.splice(i, 1);
     this.setState({ users });
  }
  
  handleSubmit(event) {
    alert('A name was submitted: ' + JSON.stringify(this.state.users));
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
          {this.createUI()}        
          <input type='button' value='add more' onClick={this.addClick.bind(this)}/>
          <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('container'));

https://jsfiddle.net/mayankshukla5031/qL83cf2v/1/

But now I want generate it with dropdown, selecting the size of input options let say 5 so dynamically 5 options fields are created.

Can anybody guide me on it please.

2
  • 1
    Please add your code Commented Dec 19, 2020 at 10:14
  • I have added the code how i created it manually but need suggestions for dropdown dynamic generation. Commented Dec 19, 2020 at 10:35

2 Answers 2

1

Somthing like this should help :

class App extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      users: [1],
      options: 1,
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  addClick(){
    const newUsers = Array.from(Array(Number(this.state.options)), (_, i) => i);
    this.setState((prevState) => ({
      users: [...prevState.users, ...newUsers],
    }));
  };

  createUI() {
    return this.state.users.map((el, i) => (
      <div key={i}>
        <input
          placeholder="First Name"
          name="firstName"
          value={el.firstName || ""}
          onChange={this.handleChange.bind(this, i)}
        />
        <input
          placeholder="Last Name"
          name="lastName"
          value={el.lastName || ""}
          onChange={this.handleChange.bind(this, i)}
        />
        <input
          type="button"
          value="remove"
          onClick={this.removeClick.bind(this, i)}
        />
      </div>
    ));
  }

  handleChange(i, e) {
    const { name, value } = e.target;
    let users = [...this.state.users];
    users[i] = { ...users[i], [name]: value };
    this.setState({ users });
  }

  removeClick(i) {
    let users = [...this.state.users];
    users.splice(i, 1);
    this.setState({ users });
  }

  handleSubmit(event) {
    alert("A name was submitted: " + JSON.stringify(this.state.users));
    event.preventDefault();
  }
  handleInput = (event) => {
    event.preventDefault();
    this.setState({ options: event.target.value });
  };
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        {this.createUI()}
        <select defaultValue={this.state.options} onChange={this.handleInput}>
          {Array.from(Array(100), (_, i) => i + 1).map((opt) => (
            <option>{opt}</option>
          ))}
        </select>
        <input
          type="button"
          value="add more"
          onClick={this.addClick.bind(this)}
        />
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Sign up to request clarification or add additional context in comments.

Comments

0

I hope this one helps. Link Output keys with ur input fields.

 function App({data}){
   const [selectedField, setSelectedField] = useState('');
   const [output, setOutput] = useState({}); // u can add a default values of the keys in inital state

   useEffect(()=>{
     if(selectedField !== ''){
       const selectedData = data.filter(el=> name === el.name);
       if(selectedData){
         setOutput(selectedData);
       }
     }
   },[selectedField, data]);

   const onDataFieldRemove = (key) => {
     setOutput(prevState => {
       delete prevState[key]; // if u dont want unwanted data in ur database or use
       // prevState[key] = null; if u want to maintain ur default keys;
       return prevState;
     });
   }

   return (<div>... add ur input fields and remove button</div>)
 }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.