Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use D3 with any Framework


    In this lesson you will learn how to use a D3 line graph with any framework. The video shows the examples of Angular, React and Cycle.js, but you can transfer the knowledge to other frameworks easily.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    As example component, we will use a simple line graph that we built in another video. The important aspect is that we do not use D3's built-in DOM manipulation, but use just generators to get us a string.

    As you can see here, we are using VanillaJS to set an attribute on a predefined element. For our purpose, we will delete those lines and simply export this line string. As you can see here, I already created a few test projects. Those are just empty scaffolds of create-cycle-app, create-react-app, and Angular CLI.

    Let's jump into our React code. In this main app, we replace all we need with an SVG, set path element with MD attribute, and of course, close the SVG again. We don't need a logo anymore. We can import the line string that we just exported and use that as our D attribute in our JSX code.

    If we save that, we see the graph, but it's weird because we haven't included the styles we created last time. We simply include the styles as well, and it looks just as we expected. Let's jump to Angular. This is the Angular component we will see here.

    First, we will change that title attribute to a path string, and it will be our line string. We'll import that, and we will adjust our template. Here's a lot of stuff in there. We will delete everything and, again, put in an SVG, put in a path with an attribute binding that will be our path string, then close the SVG and close the div, save, and we see again the same path.

    We didn't have to care about the styling because I overwrote the default app.component.css with the styles CSS. Now let's jump to Cycle.js. In here, we have a lot that we don't actually need, so let's just delete it.

    Now, we replace everything inside this div with, again, an SVG, a path with MD attribute, and close the SVG, close the div, and import the line string from our graph component. Reload and switch to Cycle app, and again, we have the graph we expect.

    You can use that for every D3 component as long as you do not use D3's direct DOM manipulation, but export strings for attributes.