~2 دقیقه مطالعه • بروزرسانی ۳۰ مهر ۱۴۰۴
Introduction
In React applications, data is often fetched asynchronously. During this process, showing feedback like “Loading…” or “Something went wrong” improves user experience. This article demonstrates how to implement conditional rendering for such states using React’s built-in hooks and JSX logic.
Managing Loading State with isLoading
First, define a boolean state to track loading:
const [isLoading, setIsLoading] = React.useState(false);Then toggle it during data fetching:
React.useEffect(() => {
setIsLoading(true);
getAsyncStories().then((result) => {
setStories(result.data.stories);
setIsLoading(false);
});
}, []);Conditional Rendering with Ternary Operator
Use a ternary operator to show either the loading message or the list:
{isLoading ? (
<p>Loading ...</p>
) : (
<List list={searchedStories} onRemoveItem={handleRemoveStory} />
)}Handling Errors with isError
Define another state to track errors:
const [isError, setIsError] = React.useState(false);Update it in the catch block:
getAsyncStories()
.then((result) => {
setStories(result.data.stories);
setIsLoading(false);
})
.catch(() => setIsError(true));Conditional Rendering with Logical &&
Use the logical && operator to show the error message only when needed:
{isError && <p>Something went wrong ...</p>}If isError is true, the message is rendered. Otherwise, nothing is shown.
Conclusion
Conditional rendering in React is essential for managing UI feedback during asynchronous operations. With useState and useEffect, we can track loading and error states, and use JSX logic to dynamically render appropriate messages. These techniques help build responsive and user-friendly interfaces.
نوشته و پژوهش شده توسط دکتر شاهین صیامی