ReactJS Component Composition Pattern

𝐇𝐓𝐌𝐋 𝐟𝐢𝐠𝐮𝐫𝐞𝐝 𝐭𝐡𝐢𝐬 𝐨𝐮𝐭 𝐝𝐞𝐜𝐚𝐝𝐞𝐬 𝐚𝐠𝐨. A <𝐬𝐞𝐥𝐞𝐜𝐭> doesn't have a prop called options. 𝐘𝐨𝐮 𝐜𝐨𝐦𝐩𝐨𝐬𝐞 <𝐨𝐩𝐭𝐢𝐨𝐧> elements inside it. A <𝐭𝐚𝐛𝐥𝐞> doesn't ask you to pass rows as a config object. You write <𝐭𝐫> 𝐚𝐧𝐝 <𝐭𝐝> yourself. The 𝐂𝐨𝐦𝐩𝐨𝐮𝐧𝐝 𝐂𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭 pattern 𝐛𝐫𝐢𝐧𝐠𝐬 this 𝐬𝐚𝐦𝐞 𝐭𝐡𝐢𝐧𝐤𝐢𝐧𝐠 𝐭𝐨 𝐑𝐞𝐚𝐜𝐭. 𝐈𝐧𝐬𝐭𝐞𝐚𝐝 𝐨𝐟 one component 𝐚𝐜𝐜𝐞𝐩𝐭𝐢𝐧𝐠 𝐞𝐯𝐞𝐫𝐲 𝐜𝐨𝐧𝐟𝐢𝐠𝐮𝐫𝐚𝐭𝐢𝐨𝐧 𝐚𝐬 𝐩𝐫𝐨𝐩𝐬, you split it 𝐢𝐧𝐭𝐨 𝐧𝐚𝐦𝐞𝐝 𝐩𝐢𝐞𝐜𝐞𝐬 that compose together. A <Section.Title> A <Section.Action> A <Section.Content> 𝐄𝐚𝐜𝐡 𝐩𝐢𝐞𝐜𝐞 is independent and 𝐜𝐮𝐬𝐭𝐨𝐦𝐢𝐳𝐚𝐛𝐥𝐞 without touching the others. 𝐂𝐨𝐧𝐭𝐞𝐱𝐭 𝐢𝐬 𝐨𝐩𝐭𝐢𝐨𝐧𝐚𝐥. For simple cases, 𝐜𝐨𝐦𝐩𝐨𝐬𝐢𝐭𝐢𝐨𝐧 𝐚𝐥𝐨𝐧𝐞 𝐢𝐬 𝐞𝐧𝐨𝐮𝐠𝐡. You only reach for context when children need to share state with each other. It fits naturally for components like the following: - A <Modal> with a header, body and footer where each part is placed and styled independently per usage - A <Card> with a header, media, body and footer where consumers compose only the parts they need - A <Tabs> with a tab list, individual triggers and content panels each controlled independently If you find yourself adding props just to make a component fit a new screen that's usually a good signal. I posted a real example of this last week where we refactored a shared button component using this pattern. Link in the comments. Patterns don't make code better. Knowing when to use them does. #ReactJS #Frontend #DesignPatterns #CleanCode #ComponentDesign

To view or add a comment, sign in

Explore content categories