Add input text boxes dynamically using button and store values in state

Viewed 25

I have been successful in dynamically generating input text boxes when a button is clicked, but I ran into problems when saving the values into state.

I have decided to start fresh again, should I be using a map or an array in my state?

I want to be able to store the value of the text box with its relating input id.

class myPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }

    render() {
        return (
            <div className="container-fluid cf">
                <div className="card">
                    <div className="card-header">
                        Test Page
                    </div >
                    <div className="card-body">
                        <form>
                            <button>Add text box</button>
                        </form>
                    </div>
                </div>
            </div>
        );
    }
};
1 Answers

The idea is kind of simple. You have a state: array of input. when button clicked, add to input array state and component will re-render to show newly added input.
(Below code is to demonstrate the idea. I'm not sure it's syntax correct)

class myPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
         inputs: []
        }
    }
    
    handleButtonClick() {
     state.inputs.push({
      id: state.inputs.length + 1,
      value: ''
     });
     setState({...state});
    }

    handleInputChange(e, inputId) {
 
     state.inputs[inputId].value = e.target.value;
     setState({...state});
    }

    render() {
        return (
            <div className="container-fluid cf">
                <div className="card">
                    <div className="card-header">
                        Test Page
                    </div >
                    <div className="card-body">
                        <form>
                            <button onClick={(e)=>{handleButtonClick();}}>Add text box</button>

                        {state.inputs.map(item=>{ return (
                          <input type="text" id={item.id} value={item.value} onChange={(e)=>{ handleInputChange(e, item.id); }}/>
                        ); })}
                        </form>
                    </div>
                </div>
            </div>
        );
    }
};
Related