Search code examples
javascriptreactjsd3.jsqueryselector

How can we use d3-funnel with React? I tried implementing it but getting some errors


import React , {useRef , useEffect} from 'react';
import D3Funnel from 'd3-funnel';

function RecruitmentFunnel() {

    useEffect(() => {
        

    var data = [
        ['Applicants', 267 , '#1e4684', '#1e4684'],
        ['Interviews', 134,  '#1e4684'],
        ['Assessments', 48,  '#1e4684'],
        ['Hired',26,  '#1e4684']
    ];

    var options = {
        width : 200,
        height : 400,
        bottomWidth : 1/2,
        bottomPinch : 0,      // How many sections to pinch
        isCurved : true,     // Whether the funnel is curved
        curveHeight : 10,     // The curvature amount
        fillType : "gradient",   // Either "solid" or "gradient"
        isInverted : false,   // Whether the funnel is inverted
        hoverEffects : true,  // Whether the funnel has effects on hover
        fontSize : '18px'
    };

    var funnel = new D3Funnel( data, options );
    funnel.draw ( "#funnel" );
    
    },[])

    return <div id="funnel"></div>;
}

export default RecruitmentFunnel;

error


Solution

  • #funnel does not yet exist when you call for it. You will need to use a ref to find it. Example:

    import { select } from "d3-selection";
    
    constructor(props) {
        this.ref = React.createRef();
    }
    
    render() {
    
        funnel.draw( d3.select(this.ref.current) );
    
        return <div ref = { this.ref } ></div>;
    }