0

I'm not very proficient with React. I'm working with a dynamic form where users should be able to dynamically add and remove input fields. I'm unable to save inputs into variables dynamically however.

Code:


class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      values: [],
      type:[],
      name: '',
      frequency: '',
    };
  } 

  handleMetric(i, event) {
     let values = [...this.state.values];
     values[i] = event.target.value;
     this.setState({ values });
     console.log("Metrics: ")
     console.log(values) 
  }

  handleThreshold(i, event) {
    let values = [...this.state.values];
    values[i] = event.target.value;
    this.setState({ values });
    console.log("Threshold: ")
     console.log(values) 
  }

  addClick(){
    this.setState(prevState => ({ values: [...prevState.values, '']}))
  }
  
  removeClick(i){
     let values = [...this.state.values];
     values.splice(i,1);
     this.setState({ values });
  }

  createUI(){
    return this.state.values.map((el, i) => 
        <div key={i}>
         <input type="text" value={el||''} onChange={this.handleChange.bind(this, i)} />
         <input type='button' value='remove' onClick={this.removeClick.bind(this, i)}/>
        </div>          
    )
 }
  
  render() {

    return (
    <div> 
       <div className="card">
          <form onSubmit={this.handleSubmit}>
         
              <Form.Item name="Type of metrics" label="Metric" htmlFor="type">
                <Select
                  value={Select}
                  onChange={this.handleMetric}
                  options={metrics}
                />
              </Form.Item>

              <Form.Item name="amount" label="Threshold Score" htmlFor="threshold">
                <Slider marks={marks} name="threshold" onChange={this.handleThreshold} />
              </Form.Item>

            </Form>

            {this.createUI()}  

            <input type='button' value='add more' onClick={this.addClick.bind(this)}/>
            <input type="submit" value="Submit" />

          </form>
        </div>
      </div>
    );
  }
}

export default App

Both handleThreshold and handleMetric functions are not working, and giving the following errors: enter image description here

enter image description here

Would really appreciate some help in getting the variables stored in the arrays dynamically.

1 Answer 1

1

Turn the class methods into class property initializers with arrow functions so this is always the component instance:

  handleMetric = (i, event) => {
     let values = [...this.state.values];
     values[i] = event.target.value;
     this.setState({ values });
     console.log("Metrics: ")
     console.log(values) 
  };

  handleThreshold = (i, event) => {
    let values = [...this.state.values];
    values[i] = event.target.value;
    this.setState({ values });
    console.log("Threshold: ")
     console.log(values) 
  };

You solved this for another callback by doing this.addClick.bind(this) inside the render method. Both approaches work. Doing the arrow function declaration means only 1 function is created in the life of the component whereas .bind in render means 1 function is created per call to render. This will likely have no recognizable performance change for your app but is something to consider.

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

3 Comments

Thank you, but it isn't working. I'm getting an error on line values[i] = event.target.value;
What error are you getting on that line now?
I got the same error as before "value not defined", but I've got it working now, thank you anyway!

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.