0

I am new to React, JavaScript, and programming in general. Forgive me if this seems super elementary.

I am trying to create a simple to do list in React to get practice. I went through a course on freecodecamp.com, so I feel like I understand enough to do this. I didn't look at any tutorials on how to create one as I want to actually do as much as I can on my own.

Right now, I am attempting to remove an li from a ul list with a button next to each line item. I am able to get it to modify the array, but it won't re-render with the line item removed. I believe that modifying state should allow the change to happen automatically, but I must be missing something basic.

The only other component is the app component, which is obviously the parent.

import React, { useRef } from 'react';
import { useState } from 'react';

function ToDoList() {
  // initialize state
  const [list, modifyList] = useState([])
  

  // function to add elements to the list
  const nameForm = useRef(null)
  const updateList = () => {
    const form = nameForm.current
    modifyList([...list,`${form['addtodo'].value}`])
  }

// remove from list
const removeListItem = (listItem) => {
  modifyList(currentArr => {
    currentArr.splice(currentArr.indexOf(listItem), 1)
    return currentArr
  })
}


// render input, buttons, and list
  return (
    <form ref={nameForm}>
      <input type="text" name={'addtodo'} placeholder='input to do'></input>
      <button type="button" onClick={updateList}>Add to list</button>
      <ul>
        {
          list.map((elem) => 
            (
              <li key={elem}>{elem} <button type='button' onClick={() => removeListItem(elem)}>X</button></li>
           )
       )
     }
      </ul>
    </form>
  );
}

export default ToDoList;

I realize my code is probably a hot mess and could be written better and maybe have the input and add button be a separate component from the to do list. I am open to other suggestions if they are needed.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181

0 Answers0