dorkycam
dorkycam

Reputation: 529

Getting text inputs to work in ReactJS

I have a few text inputs on my form that are not working correctly. I cannot see what is being typed and the fields unfocus after just one character. Here's the pieces of my code where it's at:

      constructor(props) {
        super(props);
        this.state = {
          key: uuid(),
          title: "",
          author: "",
          questions: [],
          answers: []
        };

        this.handleChange = this.handleChange.bind(this);
        this.addQuestion = this.addQuestion.bind(this);
        this.removeItem = this.removeItem.bind(this)
      }

      componentDidMount() {
        // componentDidMount() is a React lifecycle method
        this.addQuestion();
      }

      handleChange(event) {
        const target = event.target;
        const value = target.type === "checkbox" ? target.checked : target.value;
        const name = target.name;

        this.setState({
          [name]: value
        });
      }

//yada yada

render() {
//yada yada
    {this.state.questions.map((question, index) => {
                    return (
                      <li>
                      <div key={uuid()}>
                        Question
                        {question}<br />
                        <button onClick={ () => this.removeItem(index) }>
                      Remove Question
                    </button>
                        Answer Choices<br />
                        {Array.from({ length: 4 }, () => (
                          <div>
                            <input type="checkbox" key={uuid()}/>
                            <input type="text" key={uuid()} onChange={this.handleChange} />
                          </div>
                        ))}
                      </div>
                      </li>
                    );
                  })}
//yada yada
}
export default App;

I am very new to this so any tips directly related to this issue or not would be super helpful. Thanks!

Upvotes: 2

Views: 47

Answers (1)

Tholle
Tholle

Reputation: 112917

You are giving your elements unique keys each render with uuid(), which will destroy the element and mount a new one. Remove the key={uuid()} and it will work.

{this.state.questions.map((question, index) => {
  return (
    <li key={index}>
      <div>
        Question
        {question}
        <br />
        <button onClick={() => this.removeItem(index)}>
          Remove Question
        </button>
        Answer Choices<br />
        {Array.from({ length: 4 }, (_element, index) => (
          <div key={index}>
            <input type="checkbox" />
            <input type="text" onChange={this.handleChange} />
          </div>
        ))}
      </div>
    </li>
  );
})}

Upvotes: 1

Related Questions