Home > database >  Best way to write onClick multiline function?
Best way to write onClick multiline function?

Time:10-30

I have this onClick function that shows the details of the user and then sets another state back to true. Would it be better to declare this function outside of the return as it is multiline? and if so how should I write it?

 <Button onClick ={() => {setSelectedUser(user); setShowUser(true);}}>{user.name}</Button>

Here the rest of my code as reference:

const UserList = () => {
 
  const [users, setUsers] = useState([])
  const [selectedUser, setSelectedUser] = useState()
  const [showUser, setShowUser] = useState(true)
  
  const onHandleClick = () => setShowUser(false)
    
  useEffect(() => {
    fetch(URL)
      .then(res => res.json())
      .then(json => setUsers(json));
  }, [])

  return (
    <>
      <Header>      
        <h1>Contact list</h1>
      </Header>
      <Container> 
          <div>
          {users.map(user => (
            <div key={user.id}>
              <Button onClick ={() => {setSelectedUser(user); setShowUser(true);}}>{user.name}</Button>
            </div>
          ))}         
          </div> 

        {selectedUser && (
          <>
            {showUser ?
            <UserDetail 
              name={selectedUser.name} 
              username={selectedUser.username}
              email={selectedUser.email}
              address={selectedUser.address.street}
              phone={selectedUser.phone}
              company={selectedUser.company.name}
              onClick={onHandleClick}
            />
            : false}           
          </>
        )}        
      </Container>    
    </>
  )
}

CodePudding user response:

If you want to declare function outside of the JSX then you can do as:

<Button onClick={() => changeUser(user)}>{user.name}</Button>

Declaration of function

function changeUser(user) {
  setSelectedUser(user);
  setShowUser(true);
}
  • Related