Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
3 years ago
Solved

Filtering an Embedded Power BI Report via HTML inputs

Hi. I have a React web application with a power bi report embedded in it. Is there a way to filter data in a report programatically by using an html input text box in the web application?
  • Sahir_Maharaj's avatar
    Sahir_Maharaj
    3 years ago

    Here is a code example I have written in React:

     

    import React, { useState, useEffect } from 'react';
    import * as pbi from 'powerbi-client';
    
    const Report = () => {
      const [report, setReport] = useState(null);
      const [inputValue, setInputValue] = useState('');
    
      useEffect(() => {
        const embedConfiguration = {
          type: 'report',
          id: '<REPORT_ID>',
          embedUrl: '<REPORT_EMBED_URL>',
          accessToken: '<ACCESS_TOKEN>',
          tokenType: pbi.models.TokenType.Aad
        };
    
        const powerbi = new pbi.Service(
          pbi.factories.hpmFactory,
          pbi.factories.wpmpFactory,
          pbi.factories.routerFactory
        );
    
        const reportContainer = document.getElementById('reportContainer');
        const report = powerbi.embed(reportContainer, embedConfiguration);
        setReport(report);
      }, []);
    
      const handleInputChange = (event) => {
        setInputValue(event.target.value);
      };
    
      const applyFilter = () => {
        if (report) {
          report.getFilters()
            .then((filters) => {
              const newFilters = [{
                ...filters,
                $schema: "http://powerbi.com/product/schema#basic",
                target: {
                  table: "<TABLE_NAME>",
                  column: "<COLUMN_NAME>"
                },
                operator: "In",
                values: [inputValue]
              }];
    
              report.setFilters(newFilters)
                .catch((error) => console.error(error));
            })
            .catch((error) => console.error(error));
        }
      };
    
      return (
        <div>
          <input type="text" value={inputValue} onChange={handleInputChange} />
          <button onClick={applyFilter}>Filter</button>
          <div id="reportContainer" />
        </div>
      );
    };
    
    export default Report;