Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove items from an array React?

I am making a form that allows a user to build a quiz (here's my code so far)

var uuid = require("uuid-v4");
// Generate a new UUID
var myUUID = uuid();
// Validate a UUID as proper V4 format
uuid.isUUID(myUUID); // true

var questionNum = 0;

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

    this.handleChange = this.handleChange.bind(this);
    this.addQuestion = this.addQuestion.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
    });
  }

  /**
   * It's probably better to structure your questions like this:
   * this.state.questions: [{
   *         question: 'How are you?',
   *         answers: ['Good', 'Great', 'Awful'],
   *         // correctAnswer: 'Great'
   *     },
   *     {
   *         question: 'What is your name?',
   *         answers: ['Toby', 'Marco', 'Jeff'],
   *         // correctAnswer: 'Jeff'
   *     }];
   *
   * This allows you to keep better track of what questions
   * have what answers. If you're making a 'quiz' type structure,
   * you could additionally add a `correctAnswer` property.
   */

  addQuestion() {
    questionNum++;
    this.setState(previousState => {
      const questions = [...previousState.questions, "question", "hi"];
      const answers = [...previousState.answers];

      for (var i = 0; i < 4; i++) {
        answers.push({
          answerChoice: "",
          key: uuid()
        });
      }
      return { questions, answers };
    });
    console.log(
      this.state.answers,
      this.state.questions,
      questionNum,
      this.state.title,
      this.state.author
    );
  }

  render() {
    return (
      <div className="App">
        <div>
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <h1 className="App-title">Quiz Form 2.0</h1>
          </header>
          <p className="App-intro">
            To get started, edit <code>src/App.js</code> and save to reload.
          </p>
        </div>

        <div>
          <form>
            <div className="Intro">
              Give your Quiz a title:{" "}
              <input
                type="text"
                value={this.state.title}
                onChange={this.handleChange}
                name="title"
              />
              <br />
              Who's the Author?{" "}
              <input
                type="text"
                value={this.state.author}
                onChange={this.handleChange}
                name="author"
              />
              <br />
              <br />
            </div>
            <div className="questions">
              Now let's add some questions... <br />
              {// This is where we loop through our questions to
              // add them to the DOM.
              this.state.questions.map(question => {
                return <div>{question}</div>;
              })

              // This is what it would look like for the structure
              // I proposed earlier.
              // this.state.questions.map((question) {
              //   return (
              //       <div>{question.quesion}</div>
              //       {
              //           question.answers.map((answer) => {
              //               return (<div>{answer}</div>);
              //           })
              //       }
              //   );
              // })
              // This would output all questions and answers.
              }
            </div>
          </form>
          <button onClick={this.addQuestion}>Add Question</button>
        </div>
      </div>
    );
  }
}

export default App;

And I have come to the point where I want to try and be able to "Remove" a question (using a button). What my code does now is it adds objects to an array, and I have got that figured out. But now I am trying to remove Items from the array. I was thinking "ok just remove the last question" but realistically users will want to remove any of their questions. I was just curious if anyone had some tips for this, I really don't know how to start.

like image 677
dorkycam Avatar asked Dec 11 '22 06:12

dorkycam


1 Answers

If you want the user to be able to remove any question, add an onClick to the question div (or a child of the div - remember to move the onClick). The callback for that can accept an index, which refers to the element in the list to remove.

Example:

class App extends Component {
  constructor(props) {
    super(props)

    this.removeItem = this.removeItem.bind(this)
  }

  removeItem (index) {
    this.setState(({ questions }) => {
      const mQuestions = [ ...questions ]
      mQuestions.splice(index, 1)
      return { questions: mQuestions }
    })
  }

  render () {
    return (
      <div>
        ...
        { this.state.questions.map((question, index) => {
          return <div onClick={ () => this.removeItem(index) }>{ question }</div>
        }) }
      </div>
    )
  }
}
like image 67
Tyler Sebastian Avatar answered Dec 27 '22 16:12

Tyler Sebastian