<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Reactoraptor on Medium]]></title>
        <description><![CDATA[Stories by Reactoraptor on Medium]]></description>
        <link>https://medium.com/@redrunner.dev?source=rss-d0faab787f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PoJBK7DJwo5CTlQshrxYbA.png</url>
            <title>Stories by Reactoraptor on Medium</title>
            <link>https://medium.com/@redrunner.dev?source=rss-d0faab787f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:42:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@redrunner.dev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Prop spreading in React: when and where.]]></title>
            <link>https://medium.com/@redrunner.dev/prop-spreading-in-react-when-and-where-abf3eb646e5?source=rss-d0faab787f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/abf3eb646e5</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[props-in-react]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Reactoraptor]]></dc:creator>
            <pubDate>Sun, 05 Mar 2023 20:19:51 GMT</pubDate>
            <atom:updated>2023-03-06T16:15:51.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*snhi2397k-XYoN3t" /><figcaption>Photo by <a href="https://unsplash.com/@brizmaker?utm_source=medium&amp;utm_medium=referral">Alex</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi and welcome to this humble post. Whether if you are from earth or another planet, sit back and enjoy this couple of lines. In this post, you will find some insight about when and were it’s a good idea to use <strong>prop spreading in React. </strong>Let’s begin 💪</p><h3>Basic context</h3><p>According to MDN <strong>spread syntax </strong>refers to:<em> “In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.” </em>In React, this can be used to pass an (n) number of key-value to a component. For example:</p><pre>// Component Declaration 👀<br>const Component: FC&lt;ComponentProps&gt; = ({ children, ...otherProps }) =&gt; {<br>  return &lt;div {...otherProps}&gt;{children}&lt;/div&gt;;<br>};<br><br>const props = {<br>  role: &#39;button&#39;,<br>  &#39;data-testid&#39;: &#39;mr-component&#39;,<br>  style: { backgroundColor: &#39;red&#39; }<br>};<br><br>// Component consumption 🎯<br>&lt;Component {...props}&gt;If only I had more cheese 🧀&lt;/Component&gt;<br><br>// Component output 📦<br>&lt;div role=&quot;button&quot; data-testid=&quot;mr-component&quot; style=&quot;background-color: red;&quot;&gt;If only I had more cheese 🧀&lt;/div&gt;</pre><p>Looking at this, you must be thinking that this is useful. And spoiler alert, it is! ✨. But wait, then why does <a href="https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-props-no-spreading.md"><strong>eslint</strong></a> have an explicit rule to avoid this? Let’s bring a bit more light into the topic 💡</p><h3>Recurrent pitfalls</h3><p>When building components the benefits of using Typescript properly are substantial. The main one is, that it allows us to have control about the <strong>input </strong>and <strong>output, </strong>which avoid unwanted side effects. However, when we do something like ...otherProps , the code might not explicitly complain, <strong>unless you type your component properly </strong>(we will tackle it later 😉).</p><p>This might cause potential pitfalls, such as:</p><ul><li>Poor code readability.</li><li>Invalid HTML props (causing warnings).</li><li>Prop overriding.</li></ul><p>Let’s take a quick look one by one:</p><p><strong>Readability</strong></p><p>When passing props to a component, we need to remember that we might have to revisit it later, either for an iteration or for a fix. If you went for a prop spreading approach, this is what you might see:</p><pre>// I wonder what parentProps?.modal might hold inside 🤔<br>const ParentComponent: FC&lt;ParentComponentProps&gt; = (parentProps) =&gt; {<br>  return (<br>    &lt;Modal {...parentProps?.modal} /&gt;<br>  );<br>}<br></pre><p>In some cases, modalProps can be on the same file and easy to access, others, you might face an undetermined amount of component nesting, which might make your task difficult.</p><p>We could argue the fact that <strong>Typescript </strong>will ensure that the modal will receive the right props, but this might not be the case if you have some optional props. At the same time, components might not be as straightforward as they look, consider they might have variations or multiple ways of configuring them.</p><p>A more readable approach might be:</p><pre>// I can read what the modal might be printing now 🎉<br>const ParentComponent: FC&lt;ParentComponentProps&gt; = ({modal, ...otherProps}) =&gt; {<br>  const {title, subtitle, isOpen} = modal || {};  <br> <br>  return (<br>    &lt;Modal title={title} subtitle={subtitle} isOpen={isOpen} /&gt;<br>    );<br>  /&gt;;<br>}</pre><p><strong>Invalid HTML props</strong></p><p>If you had the chance to pop into the <a href="https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-props-no-spreading.md"><strong>eslint</strong></a><strong> </strong>link about props spreading, you might have read that warnings about invalid HTML props are a possibility. Let’s see how does this look like 👀</p><p>For example, a label and an input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*mQnxREjoH3U6OaO3P98kIA.png" /><figcaption>CodeSandbox example Typescript + React</figcaption></figure><p>As you can see, this code seems to be fine at first sight. We spread labelProps to the label tag and that might do the trick. However, if we take a look at the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Dsqz0qfTg7vycZm42TjpQ.png" /><figcaption>Warning of doom 💥</figcaption></figure><p>That’s right, we got something unexpected. If you check <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label"><strong>MDN</strong></a>, you might get the reason pretty quickly; turns out, the recommendation is: “<em>to programmatically set the </em><em>for attribute, use </em><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor"><em>htmlFor</em></a><em>.” </em>However, we were not warned about it. Let’s avoid prop spreading now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*-LBdPsbFvETA-Qk64xc1Mw.png" /><figcaption>CodeSandbox example Typescript + React (just no prop spreading 🎯)</figcaption></figure><p>It looks like we are getting better clues now. But why are we getting this error? The reason is related with the previous labelProps not being properly typed, which, is an absolute necessity if we go towards prop spreading. Let’s see the difference 🔬</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*gN_6e-fnMqt_CvyKuDdo7w.png" /><figcaption>labelProps typed with LabelHTMLAttributes.</figcaption></figure><p>Here, we associated labelProps to the props of the actual HTML tag. In this way, if we hover the warning, we will see the previous mistake because the code interprets that we are declaring attributes for a <strong>label</strong>. If we were to leave the object without typing, for would be considered a regular prop which would be typed as string .</p><h4>Prop overriding</h4><p>Consider the following:</p><pre>const otherProps = {<br>  className: &quot;snakes-button&quot; <br>};<br><br>&lt;Button <br>  className=&quot;cheese-button&quot; <br>  data-testid=&quot;cheese.button&quot;<br>  onClick={handleClick}<br>  aria-label=&quot;buy cheese&quot;<br>  {...otherProps}<br>&gt;<br>  Buy cheese 🧀<br>&lt;/Button&gt;</pre><p>In this example, we are only spreading 1 object while the other props are explicitly declared. Since by definition JSX represents objects by <a href="https://rossbulat.medium.com/react-native-working-with-objects-aff45bff6832">definition</a>, here we would be <strong>overriding </strong>the className prop in favour of… Well… Snakes 🐍.</p><p>For this to still work, the prop spread would need to be declared at the very beginning, which, would also be an override in favour of the manually declared one.</p><p>If multiple prop spreading occur, you might have a hard time knowing which is the final value passed down to your component.</p><h3>Benefits</h3><p>About the benefits then. Prop spreading can save a lot of time declaring every single prop. Specially if the component has a lot of parameters; even then though, elements can be broken down into more reusable chunks.</p><h4>Intermediate level spreading</h4><p>Sometimes, your component might be have more than 2 levels of depth. That being:</p><pre>[+] ParentComponent<br>└── [+] MiddleComponent<br>    └── [+] LastComponent</pre><p>It is very possible that you are explicitly mounting the props in the parent component. In the middle one, you might be getting an object as props for one of the components. In this case, you might not want to see the this props so explicitly because it is not adding any value for you. <strong>If your typing is well done and the properties are clear, you can opt for prop spreading (compromising readability).</strong></p><h4>Spread props from a function</h4><p>In other times, your component can hold a large number of properties. This might include: static information, handlers, aria attributes or data attributes. Some of this properties, for example, you might be obtaining as a result of a function.</p><p>Let’s say we have a function that builds our data attributes for Google Analytics tracking.</p><pre>export const getGAAtributes = ({<br>  country,<br>  language,<br>  label,<br>}: {<br>  country: string;<br>  language: string;<br>  label: string;<br>}) =&gt; {<br><br>  return {<br>    &#39;data-country&#39;: country,<br>    &#39;data-language&#39;: language,<br>    &#39;data-label&#39;: label<br>  }<br>};</pre><p>Later, we want to reuse this function to calculate the right attributes for a component. For this reason, we might have something like:</p><pre>const gAAtributes = getGAAtributes(&#39;France&#39;, &#39;French&#39;, &#39;Comptine d’un autre été&#39;);<br><br>&lt;MyComponent {...gaAttributes} /&gt;</pre><p>In this case, making a selective prop spreading using a function is helping us to achieve consistency in the way we create this attributes. Even if later we might add more props, this practice might come quite handy if used well.</p><h4>Building components</h4><p>When building reusable elements, passing HTML props to some elements could come in handy. A possible approximation to the problem could be:</p><pre>import { FC, HTMLAttributes } from &#39;react&#39;;<br><br>export interface ButtonProps extends HTMLAttributes&lt;HTMLButtonElement&gt; {<br>  children: string;<br>}<br><br>export const Button: FC&lt;ButtonProps&gt; = ({ children, className, ...buttonProps }) =&gt; (<br>  &lt;button {...buttonProps} className={className}&gt;<br>    {children}<br>  &lt;/button&gt;<br>);</pre><p>In this example, I’m not making explicit every single prop a button might have. Instead, I’m informing <strong>Typescript</strong> that I will be passing HTML button element properties to this component, when they are needed. This might save you a ton of work; notice here, we are not even declaring onClick .</p><p>If we wanted to do this process prop by prop, this interface could’ve been very, very long. Since <strong>Typescript </strong>is making sure you can only pass HTML button props, <strong>in my opinion, </strong>prop spreading here is relatively safe.</p><h3>Conclusion</h3><p>All things considered, is that there is no explicit need to demonise prop spreading 👹. Several practices and patterns might come in handy depending on the occasion. Understanding the risks and tradeoffs helps us build quality code to achieve what we want and that is always a fine addition to our tool belt.</p><p>Thank you very much for taking the time to read. I’m a humble developer trying to help the community and grow as a professional. If you have any input that can improve the quality of this article, do not hesitate to put it in the comments. 😉</p><p>If you made it this far:</p><p><a href="https://media0.giphy.com/media/7aBE32jCr6lOhtuE9v/giphy.gif?cid=ecf05e47vh1ikzbrg8j2svyhgnu999weajbmktitew5d5j6l&amp;rid=giphy.gif&amp;ct=g">You Rock GIF - Find &amp; Share on GIPHY</a></p><p><strong>Bibliography</strong></p><blockquote><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax</a></blockquote><blockquote><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label">https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label</a></blockquote><blockquote><a href="https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-props-no-spreading.md">https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-props-no-spreading.md</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abf3eb646e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>