Today marks another step in my React learning journey, and it’s all about Lifecycle Methods and Conditional Rendering. Understanding how React components are born, grow, and eventually leave the DOM has been a game-changer for me. Add to that the ability to conditionally display content based on user interactions, and suddenly, building dynamic, user-friendly apps feels so sweet!
Lifecycle Methods in React Functional Components
Lifecycle has 3 steps:
1.Initial Step (Mounting Phase):
useEffect(() => { console.log("Component mounted"); }, []);
2.Update Step:
useEffect(() => { console.log("State or props updated!"); }, [dependency1, dependency2]);
3. Exit / Unmounting Phase:
useEffect(() => { const handleResize = () => console.log("Resized!"); window.addEventListener("resize", handleResize); return () => { window.removeEventListener("resize", handleResize); console.log("Component unmounted, cleanup done!"); }; }, []);
This technique is essential for dynamically rendering components or elements based on conditions.
Ternary Operator
UserGreetings example:
return props.isLoggedIn ? ( <h2 className='welcome-message'>Welcome {props.username}</h2> ) : ( <h2 className='login-prompt'>Please log in to continue</h2> );
Short-Circuit Evaluation
For simpler conditions, you can use && to render components only when a condition is true:
return props.isLoggedIn && <h2>Welcome, {props.username}</h2>;
Inline Conditional Styles
You can also dynamically style components:
const messageStyle = props.isLoggedIn ? { color: "green" } : { color: "red" }; return <h2> <p><em>This keeps getting better day-by-day</em></p>
The above is the detailed content of My React Journey: Day 26. For more information, please follow other related articles on the PHP Chinese website!