<?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 Aidan Freeman on Medium]]></title>
        <description><![CDATA[Stories by Aidan Freeman on Medium]]></description>
        <link>https://medium.com/@freeman.aidan?source=rss-e9cc891daf35------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1-7pKzhU0HCcZ3ypsH_ETA.jpeg</url>
            <title>Stories by Aidan Freeman on Medium</title>
            <link>https://medium.com/@freeman.aidan?source=rss-e9cc891daf35------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:30:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@freeman.aidan/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[How to conditionally style elements on hover events with React]]></title>
            <link>https://blog.stackademic.com/how-to-conditionally-style-elements-on-hover-events-with-react-d9d17467dd1b?source=rss-e9cc891daf35------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9d17467dd1b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Aidan Freeman]]></dc:creator>
            <pubDate>Thu, 09 Nov 2023 08:02:05 GMT</pubDate>
            <atom:updated>2023-11-13T09:44:39.857Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Conditionally Style Elements on Hover Events with React</h3><p><strong><em>Hey everyone, welcome to this new series I’m starting to write called This Week I Learned (TWIL)! The aim of this series is to write an article about what I learnt this week as a Software Engineer.</em></strong></p><p><strong>Quick introduction to me, I’m a Software Engineer currently based in Barcelona. I mainly work with JavaScript but have experience with other languages, so these articles could really be about anything!</strong></p><p>This week I was facing a problem where we are creating a custom date range picker in React and I wanted to highlight the range of dates when hovering over a date after selecting the first date. This is quite a common problem, but a lot of solutions that I found involved jQuery which made them irrelevant to me.</p><p>Instead, I used the useState hook to set a Map object which then sets a style to those elements in that range.</p><h3>1. The Calendar</h3><p>For the purposes of this example, I will just use a hardcoded month with 31 days. There are lots of complexities and edge cases that you could take into account with a custom calendar, like not selecting past dates and a range across multiple months, but I won’t focus on that now.</p><p>The calendar component currently looks like so:</p><pre>import React from &#39;react&#39;;<br>import styles from &#39;./calendar.module.scss&#39;;<br>import classNames from &#39;classnames&#39;;<br><br>const generateDateMap = (dateFrom, dateTo) =&gt;<br>  [...Array(dateTo - dateFrom + 1).keys()].map((i) =&gt; i + dateFrom);<br><br>export const Calendar = () =&gt; {<br>  const [dateFrom, setDateFrom] = React.useState(null);<br>  const [dateTo, setDateTo] = React.useState(null);<br>  const [dateRangeMap, setDateRangeMap] = React.useState(null);<br>  const handleDayClick = (day) =&gt; {<br>    if (dateFrom &amp;&amp; !dateTo &amp;&amp; day &gt; dateFrom) {<br>      setDateTo(day);<br>      setDateRangeMap(generateDateMap(dateFrom, day));<br>    } else {<br>      setDateFrom(day);<br>      setDateTo(null);<br>      setDateRangeMap(null);<br>    }<br>  };<br>  const renderDay = (day) =&gt; {<br>    const isDateFrom = dateFrom &amp;&amp; dateFrom === day;<br>    const isDateTo = dateTo &amp;&amp; dateTo === day;<br>    const isWithinDateRange =<br>      dateRangeMap &amp;&amp; dateRangeMap.includes(day);<br>    const isSelected = isDateFrom || isDateTo || isHoverDateTo;<br>    const dayStyles = classNames(styles.day, {<br>      [styles.day_from]: isWithinDateRange &amp;&amp; isDateFrom,<br>      [styles.day_to]: isDateTo,<br>      [styles.day_scoped]: isWithinDateRange,<br>    });<br>    const dayContainerStyles = classNames(styles.day_container, {<br>      [styles.day_container_selected]: isSelected,<br>      [styles.day_container_from]: isDateFrom,<br>      [styles.day_container_to]: isDateTo,<br>    });<br>    return (<br>      &lt;div<br>        key={day}<br>        className={dayStyles}<br>        onClick={() =&gt; handleDayClick(day)}<br>      &gt;<br>        &lt;div className={dayContainerStyles}&gt;<br>          &lt;span&gt;{day}&lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  };<br>  return (<br>    &lt;div className={styles.days_container}&gt;<br>      {Array.from({ length: 31 }, (_, i) =&gt; i + 1).map((day) =&gt;<br>        renderDay(day)<br>      )}<br>    &lt;/div&gt;<br>  );<br>};</pre><p>This component renders a 31 day month which allows you to select a range of dates in that set of days. I have used the classnames package to reduce the conditional styles complexity and make this code more readable. Each day has a background and a container for styling purposes. We have 3 state variables which do the following:</p><ul><li>dateFrom - number of the starting date selected</li><li>dateTo - number of the end date selected</li><li>dateRangeMap - array which contains the dates in the range</li></ul><p>We have a click event handler which sets these state variables meaning, when we select the dates, we get a result like this:</p><h3>2. Implement Hover Styles</h3><p>So we have this behaviour for selecting when we click this range of dates, but what if we want to show this selection when we hover over our potential selection of dates?</p><p>A solution to this would be to use the mouse enter and mouse leave events to set a state variable which can then be used to set a conditional style specifically for these events.</p><p>First off, we initialise that state variable:</p><pre>const [hoverDateTo, setHoverDateTo] = React.useState(null);</pre><p>Then we add our mouse enter handler:</p><pre>const handleDayHover = (day) =&gt; {<br>  if (!dateFrom || dateTo) {<br>    return;<br>  }<br>  setHoverDateTo(day);<br>  setDateRangeMap(generateDateMap(dateFrom, day));<br>};</pre><p>This will only change the state of our component if we are in the process of selecting our dates. If we are, it sets our hover state variable and also sets our date range so the styles are applied as per our conditions.</p><p>We also need to clear this state one leaving the element we are hovering on:</p><pre>const handleDayMouseLeave = () =&gt; {<br>  setHoverDateTo(null);<br>  if (!dateTo) {<br>    setDateRangeMap(null);<br>  }<br>};</pre><p>This clears the hover state variable when leaving the element. Notice we only clear the date range if the dateTo hasn’t been selected. This is so the date range isn’t cleared when leaving the day element after selecting it as our dateTo.</p><p>Next, we update our conditional styles:</p><pre>const isHoverDateTo = hoverDateTo &amp;&amp; hoverDateTo === day;<br><br>const dayStyles = classNames(styles.day, {<br>  [styles.day_from]: isWithinDateRange &amp;&amp; isDateFrom,<br>  [styles.day_to]: isDateTo || isHoverDateTo,<br>  [styles.day_scoped]: isWithinDateRange,<br>});<br>const dayContainerStyles = classNames(styles.day_container, {<br>  [styles.day_container_selected]: isSelected,<br>  [styles.day_container_from]: isDateFrom,<br>  [styles.day_container_to]: isDateTo || isHoverDateTo,<br>});</pre><p>We check against the hover variable and apply the same styles as if it was selected on hover.</p><p>Finally, we add the events to the element we return from the renderDay method:</p><pre>return (<br>  &lt;div<br>    key={day}<br>    className={dayStyles}<br>    onClick={() =&gt; handleDayClick(day)}<br>    onMouseEnter={() =&gt; handleDayHover(day)}<br>    onMouseLeave={handleDayMouseLeave}<br>  &gt;<br>    &lt;div className={dayContainerStyles}&gt;<br>      &lt;span&gt;{day}&lt;/span&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>);</pre><p>Here is the end result!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*Pjod1MTGBwP6l-f6nCbAFw.gif" /></figure><h3>3. Conclusion</h3><p>And we are done! We now are applying styles to other elements different from those that a user will be focused on.</p><p>I hope this has been a useful read and that you can apply this to existing or future projects you are/will be working on. Until next week!</p><p><em>If you have any feedback, don’t hesitate to leave a comment. I hope to keep this up every week so if you like this format, let me know!</em></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9d17467dd1b" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-conditionally-style-elements-on-hover-events-with-react-d9d17467dd1b">How to conditionally style elements on hover events with React</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>