React / 20
Config-driven UI
Build the screen from data instead of hard-coding it, so the same components can show different layouts per city, user or experiment. Plus safe reading of messy API data.
Plan the screen as components
Before any code, sketch the tree. For our food app, "Tasty Bites":
- Header: logo, nav links, cart
- Body: search, then a list of RestaurantCards (image, name, cuisines, rating, delivery time)
- Footer: links, address, contact
Each box becomes a component. The config then decides which boxes appear and what goes in them.
One codebase, many screens
Chennai
config from the server
banner: "Free delivery"
sections: [offers, restaurants]what the user sees
Pune
config from the server
banner: null
sections: [restaurants]what the user sees
The server sends something like this:
const homeConfig = {
banner: { text: "Free delivery till 9 pm" },
sections: [
{ id: "s1", type: "offers", title: "Deals for you" },
{ id: "s2", type: "restaurants", title: "Restaurants near you" },
],
};And one component renders any version of it:
const SECTIONS = { offers: OffersRow, restaurants: RestaurantList };
export default function Home({ config }) {
return (
<main>
{config.banner && <Banner text={config.banner.text} />}
{config.sections.map((s) => {
const Section = SECTIONS[s.type];
return Section ? <Section key={s.id} title={s.title} /> : null;
})}
</main>
);
}SECTIONSmaps a type name from the data to a component.Sectionis capitalised on purpose: JSX treats lowercase names as HTML tags.- Unknown types render
null, so an old app version doesn't crash on a new section type.
Real data is messy: optional chaining
API responses are deeply nested, and fields go missing. Reading res.info.sla.deliveryTime throws if info or sla isn't there. Optional chaining (?.) stops and returns undefined instead:
export default function RestaurantCard({ resData }) {
const { name, cuisines = [], avgRating } = resData?.info ?? {};
const eta = resData?.info?.sla?.deliveryTime;
return (
<div className="card">
<h3>{name}</h3>
<p>{cuisines.join(", ")}</p>
<p>★ {avgRating ?? "New"}</p>
<p>{eta ? `${eta} min` : "Delivery time unknown"}</p>
</div>
);
}a?.bgivesundefinedifaisnullorundefined, instead of throwing.x ?? fallback(nullish coalescing) uses the fallback only whenxisnullorundefined.cuisines.join(", ")turns["Biryani", "Kebabs"]into"Biryani, Kebabs".
Don't
Destructure straight from ?.
const { name } = resData?.info; // TypeError if info is missingresData?.info safely gives undefined, but destructuring undefined still throws.
Do
Give it something to destructure
const { name } = resData?.info ?? {}; // name is undefined, no crashGotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
