tezvyn:

Designing a Card component API

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

clean component API design.

OUTLINE

simple props for title and image, but children or slots for arbitrary content instead of a string prop, keeping it composable.

RED FLAG

passing HTML as a string or via dangerouslySetInnerHTML.

WHAT THIS TESTS Whether you can design an ergonomic, safe component API and know when to use props versus composition.

A GOOD ANSWER COVERS Split the API by how variable each piece is. Title and image are simple, bounded values, so model them as scalar props: a title string, an image URL, and crucially an alt text prop so the image is accessible. The main content is the part that varies from plain text to rich markup, so model it as children or a slot rather than a content prop. Children let a caller pass a string, several elements, or another component naturally, and the framework handles escaping, so you avoid injecting raw HTML. This keeps the Card composable: it owns layout and chrome, the caller owns the body. Provide sensible defaults, mark alt as required, and keep the prop surface small so the component stays easy to use and maintain.

COMMON WRONG ANSWERS Accepting the body as an HTML string and rendering it with innerHTML or dangerouslySetInnerHTML opens XSS risk and loses composability. Adding a separate prop for every possible content shape bloats the API. Omitting alt text makes the image inaccessible. Putting layout decisions in props the caller should control via children.

LIKELY FOLLOW-UPS When is a render prop or named slot better than children? When you need multiple distinct content regions, like header and footer. How do you keep the image accessible? Required alt, empty alt for decorative images. How do you prevent layout breakage from arbitrary content? Constrain with container styles, not by restricting children.

ONE CONCRETE EXAMPLE A Card takes title and imageUrl plus alt as props and renders the body from children. One caller passes a plain string as children and gets escaped text. Another passes a paragraph and a button as children and they render inside the card body. Neither caller passes HTML as a string, so there is no injection risk, and the Card stays responsible only for its frame and layout.

Read the original → react.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.