Sobes.tech
Middle+

React task (3 sub-tasks): 1) Fix the user edit form — clicking on a username in the list should populate the input form with that name. 2) The edit form should not re-render when typing in the search field (optimization with React.memo). 3) When selecting a user from the list, the search field should reset.

sobes.tech AI

Answer from AI

To solve the task with a user editing form in React:

  1. Inserting the username into input on click:

    • In the user list, when clicking on a name, call a function that updates the selected user state.
    • In the editing form, use this state to set the input value.
  2. Optimizing the editing form with React.memo:

    • Wrap the editing form component in React.memo to prevent unnecessary re-renders.
    • Ensure that props passed to the form do not change unnecessarily (for example, use useCallback and useMemo for functions and data).
  3. Reset search field when selecting a user:

    • When selecting a user, call a function that clears the search field state.

Code example:

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

const UserForm = React.memo(({ userName, onChange }) => {
  console.log('Form render');
  return (
    <input value={userName} onChange={onChange} />
  );
});

export default function UserList() {
  const [users] = useState(['Alice', 'Bob', 'Charlie']);
  const [selectedUser, setSelectedUser] = useState('');
  const [search, setSearch] = useState('');

  const handleUserClick = useCallback((name) => {
    setSelectedUser(name);
    setSearch(''); // reset search
  }, []);

  const handleInputChange = useCallback((e) => {
    setSelectedUser(e.target.value);
  }, []);

  const handleSearchChange = useCallback((e) => {
    setSearch(e.target.value);
  }, []);

  const filteredUsers = users.filter(u => u.toLowerCase().includes(search.toLowerCase()));

  return (
    <div>
      <input
        placeholder="Search users"
        value={search}
        onChange={handleSearchChange}
      />
      <ul>
        {filteredUsers.map(user => (
          <li key={user} onClick={() => handleUserClick(user)}>{user}</li>
        ))}
      </ul>
      <UserForm userName={selectedUser} onChange={handleInputChange} />
    </div>
  );
}

In this example:

  • Clicking on a username inserts it into the form.
  • The form is wrapped in React.memo to prevent re-rendering when the search field changes.
  • When a user is selected, the search field is cleared.