Day-15 React with Me
Higher Order Component(HOC)
A higher-order component (HOC) in React is a pattern for reusing component logic. An HOC is a function that takes a component and returns a new component with additional props or behavior. It’s a way to compose components for code reuse.
Real-World Use Cases
Access Control: Conditionally render components based on user permissions or authentication state.
Data Fetching: Handle data fetching logic and pass the fetched data as props to the wrapped component.
Theming: Inject theme-related props into components.
Error Handling: Wrap components with error boundaries to catch and handle errors gracefully.
export const withBestSellerLabel = (RestaurantCard) => {
return (props) => {
return (
<div>
<label className="absolute z-10 m-2 px-2 bg-black text-xs text-white">
Best
</label>
<RestaurantCard {...props} />
</div>
);
};
};
used this to create label of best on good rated restaurants.
Lifting the state up
Lifting state up in React refers to the practice of moving the state to the nearest common ancestor of the components that need to share this state. This approach allows multiple components to access and update shared state consistently.
Why Lift State Up?
When multiple components need to share and synchronize their state, it's often more efficient to manage the state in a single location rather than having each component manage its own state independently. By lifting the state up to a common ancestor, you can pass the state down as props to the components that need it, ensuring they remain in sync.
How to Lift State Up
Identify the common ancestor: Find the closest common parent component of the components that need to share state.
Move the state to the common ancestor: Define the state and any related functions in this common ancestor.
Pass the state and functions as props: Pass the state and any state-modifying functions down to the child components via props.
Accordion UI
Created an Accordion using coitional rendering.
The
showItems && ...
part is a logical AND (&&
) operator used for conditional rendering in React.If
showItems
istrue
, the right-hand side of the&&
operator is evaluated and rendered.If
showItems
isfalse
, the entire expression evaluates tofalse
, and nothing is rendered.
const [showItems, setShowItems] = useState(false);
{showItems && itemCards.map((menuItem) => (
<MenuItems
key={menuItem?.card?.info.id}
menuItem={menuItem?.card?.info}
/>
))}