Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

javascript - How to set checked/unchecked functionality on Html table in Reactjs

I have an array of Json objects('filteredUsers' in below code) and I'm mapping them to a html table. Json object would look like {id: xyz, name: Dubov}

The below code would display a html table with a single column or basically a list. Each row will have name of user and a grey checkbox(unchecked) next to it initially. I want to select users in the table and when I select or click on any item in table, the checkmark has to turn green(checked).

            <table className="table table-sm">
              {this.state.filteredUsers && (
                <tbody>
                  {this.state.filteredUsers.map((user) => (
                    <tr key={user.id}>
                      <td onClick={() => this.selectUser(user)}>
                        
                        <span>{user.name}</span>               //Name

                        <div className={user.selected? "checked-icon": "unchecked-icon"}>   //Checkmark icon
                           <span class="checkmark"> </span>
                         </div>

                      </td>
                    </tr>
                  ))}
                </tbody>
              )}
            </table>

I tried setting a 'selected' key to each object. Initially object doesn't have 'selected' key so it will be false(all unchecked). I set onClick method for 'td' row which sets 'selected' key to object and sets it to true. Below function is called onClick of td or table item.

  selectUser = (user) => {
    user.selected = !user.selected;
  };

Now the issue is this will only work if I re-render the page after every onClick of 'td' or table item. And I'm forced to do an empty setState or this.forcedUpdate() in selectUser method to trigger a re-render. I read in multiple answers that a forced re-render is bad.

Any suggestions or help would be highly appreciated. Even a complete change of logic is also fine. My end goal is if I select an item, the grey checkmark has to turn green(checked) and if I click on it again it should turn grey(unchecked). Similarly for all items. Leave the CSS part to me, but help me with the logic. Thanks.

question from:https://stackoverflow.com/questions/65830415/how-to-set-checked-unchecked-functionality-on-html-table-in-reactjs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about something like this:

const Users = () => {
  const [users, setUsers] = useState([])

  useEffect(() => {
    // Fetch users from the API when the component mounts
    api.getUsers().then((users) => {
      // Add a `selected` field to each user and store them in state
      setUsers(users.map((user) => ({ ...user, selected: true })))
    })
  }, [])

  const toggleUserSelected = (id) => {
    setUsers((oldUsers) =>
      oldUsers.map((user) =>
        user.id === id ? { ...user, selected: !user.selected } : user
      )
    )
  }

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id} onClick={() => toggleUserSelected(user.id)}>
          <span>{user.name}</span>

          <div className={user.selected ? "checked-icon" : "unchecked-icon"}>
            <span class="checkmark" />
          </div>
        </li>
      ))}
    </ul>
  )
}

I've used hooks for this but the principles are the same.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...