I made a mistake, I make lots of them, it is how you learn so I always view it as a good thing. This is something I’ve seen lots and lots of other people do, so wanted to share it. In React how do you conditional render a component?
Okay, so, technically it isn’t a mistake, it is more of a preference thing, but it is still a good one to know.
So here is a simple bit of code to get a list of users, and then pass them to a component that will display them.
import React from 'react';
import UserList from './UserList';
import Loading from './Loading';
function App() {
const [users, setUsers] = React.useState([]);
// Make API call to retrieve user data on component mount
React.useEffect(() => {
fetch('https://example.com/api/users')
.then(response => response.json())
.then(data => setUsers(data.users))
.catch(error => console.error(error));
}, []);
return (
{users.length ?
<div>
<UserList users={users} />
</div>
:
undefined
}
);
}
export default App;
In the return, you can see that we only display the user list if we have any, we do this by checking the length. This is how I have usually done things, and I do find it readable, but there is another way that is nice.
return (
<div>
<users.length > 0 && <UserList users={users} />
</div>
);
This code displays the same result but combines the check onto one line. We have to test if the length is greater than zero because just checking length returns an int, checking if it is greater than zero gives us true/false. So if we have a length greater than zero and a return from UserList then the list will display.
Conclusion
Both methods do work, it all comes down to which you find more readable. Personally, I now find the second method more readable and have been using it for my own projects, but for shared code I’ve still been using the first method as that seems to be more common.
Facebook Comments