<?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 zouhair on Medium]]></title>
        <description><![CDATA[Stories by zouhair on Medium]]></description>
        <link>https://medium.com/@zou.ridaoui?source=rss-79fdc418e4d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*D1Q6-wCtsOXgZFsPKVKxMA.jpeg</url>
            <title>Stories by zouhair on Medium</title>
            <link>https://medium.com/@zou.ridaoui?source=rss-79fdc418e4d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:42:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zou.ridaoui/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[Building Dynamic Pivot Tables in React: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@zou.ridaoui/building-dynamic-pivot-tables-in-react-a-step-by-step-guide-21d7169b1843?source=rss-79fdc418e4d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/21d7169b1843</guid>
            <category><![CDATA[pivot-tables]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[zouhair]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 08:05:29 GMT</pubDate>
            <atom:updated>2025-04-03T13:41:59.788Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>pivot table</strong> is a powerful tool used for <strong>summarizing, analyzing, and reorganizing data</strong> in a structured format. It allows users to dynamically group, filter, and aggregate data based on different attributes, making it easier to identify <strong>patterns, trends, and insights</strong> within large datasets. Pivot tables are widely used in data analysis, business intelligence, and reporting applications.</p><p>In this tutorial, we’ll <strong>build a dynamic pivot table in React</strong> step by step, allowing us to structure and visualize data efficiently.</p><h3>Final Expected Result</h3><p>By the end of this tutorial, you will have a fully functional <strong>pivot table</strong> that dynamically organizes data based on multiple row filters. Users will be able to group data by different attributes — such as <strong>categories, dates, or regions</strong> — allowing for a structured and hierarchical view of the dataset. This interactive table will summarize key metrics efficiently, making it easy to analyze trends, compare values, and gain insights from complex data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lryz6NgyB09f1CHXaY6mMA.png" /><figcaption>As an example with only one row filter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1g2KRoNwdWC-WTZa6jcTA.png" /><figcaption>With 2 rows filter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qyXhuH2-y7qmAgLvLUk5MA.png" /><figcaption>With multi rows filter</figcaption></figure><h3>Breaking Down the Pivot Table Structure</h3><p>The pivot table consists of <strong>two main sections</strong>:</p><ol><li><strong>Left Table (Side Table)</strong> — Displays dynamically grouped row labels.</li><li><strong>Main Table</strong> — Displays aggregated values based on selected columns and metrics.</li></ol><p>To achieve this, we need to <strong>preprocess the data</strong>, which involves:</p><ul><li>Extracting headers for the main table.</li><li>Structuring hierarchical row data for proper grouping.</li><li>Organizing columns and values for efficient calculations.</li></ul><p>This preprocessing ensures that the pivot table dynamically updates based on user selections. Now, let’s break down each part in detail!</p><h3>Pivot Table Component (Pivot.js)</h3><pre>import React, { useState, useEffect } from &#39;react&#39;;<br>import { RightTable } from &quot;./columns&quot;;<br>import { LeftTable } from &#39;./leftTable&#39;;<br>import &quot;./pivot.css&quot;;<br>import { headsHandle, handleRows, handleMainCols } from &#39;../../utils/utils&#39;;<br><br>export const Pivot = ({ data, rows, cols, value }) =&gt; {<br>    const [heads, setHead] = useState([]);<br>    const [sideRow, setSideRow] = useState([]);<br>    const [columns, setCols] = useState([]);<br><br>    useEffect(() =&gt; {<br>        setHead(headsHandle(cols, data));<br>    }, [data, rows, cols, value]);<br><br>    useEffect(() =&gt; {<br>        setSideRow(handleRows(data, rows));<br>    }, [data, rows, cols, value]);<br><br>    useEffect(() =&gt; {<br>        setCols(handleMainCols(data, rows, cols, value));<br>    }, [data, rows, cols, value]);<br><br>    return (<br>        &lt;div className=&quot;pivot-table&quot;&gt;<br>            &lt;div className=&quot;side-table&quot;&gt;<br>                &lt;LeftTable filters={rows} rows={sideRow} /&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;main-table&quot;&gt;<br>                &lt;RightTable cols={columns} heads={heads} /&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    );<br>};</pre><h3>Data Processing (utils.js)</h3><p>The utils.js file contains helper functions for processing raw data into a structured format.</p><h3>1. Extracting Unique Column Headers</h3><pre>export const headsHandle = (category, data) =&gt; ([...new Set(data.map(e =&gt; e[category]))]);</pre><p>This function retrieves unique column headers from the dataset.</p><h3>2. Handling Row Data for the Side Table</h3><pre>export const handleRows = (data, rows) =&gt; {<br>    const rowsObject = {};<br>    data.forEach((item) =&gt; {<br>        let current = rowsObject;<br>        rows.forEach((row) =&gt; {<br>            current = (current[item[row]] = current[item[row]] || {});<br>        });<br>    });<br>    return rowsObject;<br>};</pre><p>This function organizes row data hierarchically for proper grouping in the side table.</p><h3>3. Processing Column Data for the Main Table</h3><pre>export const handleMainCols = (data, rows, cols, value) =&gt; {<br>    const lastCol = rows[rows.length - 1];<br>    const filter = [lastCol, cols, value];<br><br>    const colsObject = {};<br>    data.forEach((item) =&gt; {<br>        let current = colsObject;<br>        filter.forEach((col) =&gt; {<br>            current = (current[item[col]] = current[item[col]] || {});<br>        });<br>    });<br>    return colsObject;<br>};</pre><p>This function structures the main table’s column data, ensuring alignment between both tables.</p><h3>Left Table Component (LeftTable.js)</h3><p>The <strong>left-side table</strong> contains <strong>grouped-by filters</strong>, which enable users to categorize data by attributes such as <strong>categories, or regions</strong>. This hierarchical structure allows users to <strong>drill down into details</strong> without losing the dataset’s organization.</p><h3>Key Functionalities of LeftTable</h3><ul><li><strong>Processes hierarchical row data using </strong><strong>renderRows</strong>.</li><li><strong>Renders grouped labels</strong> with proper row merging (rowSpan).</li></ul><h3>Code Implementation</h3><h4>How renderRows Works:</h4><ul><li><strong>Base Case (Exit Condition):</strong> If the row data is not in an object format (e.g., null or a primitive value), the function returns an empty array, which halts further processing.</li><li><strong>Recursive Call:</strong> For each row, the function checks if there are nested rows. If nested data exists, it recursively calls itself to process the deeper levels.</li><li><strong>Row Span Calculation:</strong> For each group, the number of nested rows (rowSpan) is calculated. This ensures that if a label appears across multiple rows, it will span the necessary number of cells, merging them properly.</li><li><strong>Row Assembly:</strong> The function constructs the table rows by pushing the label (key) and its associated rowSpan, followed by the nested rows.</li></ul><pre>const renderRows = (rows) =&gt; {<br>    if (typeof rows !== &quot;object&quot; || rows === null) {<br>        return [];<br>    }<br><br>    let elements = [];<br><br>    for (let key of Object.keys(rows)) {<br>        const nestedRows = renderRows(rows[key]);<br>        const rowSpan = nestedRows.length || 1;<br><br>        elements.push([{ key, rowSpan }, ...nestedRows[0] || []]);<br>        elements.push(...nestedRows.slice(1));<br>    }<br><br>    return elements;<br>};</pre><p>Rendering the Left Table Component</p><pre>export const LeftTable = ({ filters, rows }) =&gt; {<br>    // Process the rows into a renderable format<br>    const processedRows = renderRows(rows);<br>    <br>    return (<br>        &lt;div className=&quot;left-tables&quot;&gt;<br>            &lt;table&gt;<br>                &lt;thead&gt;<br>                    &lt;tr&gt;<br>                        {/* Render column headers (filters) */}<br>                        {filters.map((filter, index) =&gt; (<br>                            &lt;td key={index} style={{ background: &quot;#DDD&quot;, textAlign: &quot;center&quot; }}&gt;<br>                                {filter}<br>                            &lt;/td&gt;<br>                        ))}<br>                    &lt;/tr&gt;<br>                &lt;/thead&gt;<br>                &lt;tbody&gt;<br>                    {/* Render processed rows */}<br>                    {processedRows.map((row, rowIndex) =&gt; (<br>                        &lt;tr key={rowIndex}&gt;<br>                            {row.map((item, colIndex) =&gt;<br>                                item ? (<br>                                    &lt;td key={colIndex} rowSpan={item.rowSpan}&gt;<br>                                        {item.key}<br>                                    &lt;/td&gt;<br>                                ) : null<br>                            )}<br>                        &lt;/tr&gt;<br>                    ))}<br>                &lt;/tbody&gt;<br>            &lt;/table&gt;<br>        &lt;/div&gt;<br>    );<br>};</pre><h3>Right Table Component (RightTable.js)</h3><p>The RightTable component is responsible for rendering the <strong>main table</strong>, which displays <strong>aggregated data</strong> with <strong>conditional styling</strong>.</p><h3>Key Functionalities</h3><ul><li><strong>Applies color styles</strong> to data cells based on values.</li><li><strong>Processes column values dynamically</strong>.</li><li><strong>Calculates totals</strong> for each row.</li></ul><h3>Code Implementation</h3><pre>export const RightTable = ({ cols, heads }) =&gt; {<br>    const styles = (v) =&gt; {<br>        if (!v) return { background: &quot;red&quot;, color: &quot;white&quot; };<br>        if (Number(v) &lt; 500) return { background: &quot;yellow&quot;, color: &quot;red&quot; };<br>        if (Number(v) &lt; 1500) return { background: &quot;indigo&quot;, color: &quot;white&quot; };<br>        if (Number(v) &lt; 3000) return { background: &quot;purple&quot;, color: &quot;white&quot; };<br>        return { background: &quot;blue&quot;, color: &quot;white&quot; };<br>    };<br><br>    const renderCells = (obj) =&gt; {<br>        return Object.entries(obj).map(([key]) =&gt; {<br>            let values = Object.entries(obj[key]).map(e =&gt; ({ [e[0]]: Object.keys(e[1])[0] }));<br>            let total = 0;<br>            return (<br>                &lt;tr key={key}&gt;<br>                    {heads.map((e, i) =&gt; {<br>                        const value = values.find(el =&gt; el[e])?.[e] || &quot;0&quot;;<br>                        total += parseInt(value) || 0;<br>                        const style = styles(value);<br>                        return (<br>                            &lt;td key={i} style={{ background: style.background, color: style.color, textAlign: &quot;center&quot; }}&gt;<br>                                {value}<br>                            &lt;/td&gt;<br>                        );<br>                    })}<br>                    &lt;td className=&quot;total-cell&quot; style={{ background: &quot;green&quot;, color: &quot;yellow&quot;, textAlign: &quot;center&quot; }}&gt;<br>                        {total}<br>                    &lt;/td&gt;<br>                &lt;/tr&gt;<br>            );<br>        });<br>    };<br><br>    return (<br>        &lt;table&gt;<br>            &lt;tbody&gt;<br>                &lt;tr&gt;<br>                    {heads.map((e, i) =&gt; (<br>                        &lt;td key={i} style={{ background: &quot;#DDD&quot;, textAlign: &quot;center&quot; }}&gt;{e}&lt;/td&gt;<br>                    ))}<br>                    &lt;td style={{ background: &quot;#DDD&quot;, textAlign: &quot;center&quot; }}&gt;Totals&lt;/td&gt;<br>                &lt;/tr&gt;<br>                {renderCells(cols)}<br>            &lt;/tbody&gt;<br>        &lt;/table&gt;<br>    );<br>};</pre><h3>Conclusion</h3><p>By following these steps, we have built a <strong>dynamic pivot table</strong> in React. It preprocesses data, structures it hierarchically, and updates dynamically based on user input. 🚀</p><p>You can find full code in this repo: <a href="https://github.com/zouhair94/pivot_table">https://github.com/zouhair94/pivot_table</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21d7169b1843" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>