title: Use React+D3 in Express
body: <p>I am trying to use D3 in a React component <em>within an Express app</em>. It seems like it should be a rather easy task, but following various tutorials not targeted to an Express app did not work: in the example below, I get an empty svg (<code>&lt;!DOCTYPE html&gt;&lt;div&gt;&lt;p&gt;D3 Example&lt;/p&gt;&lt;svg&gt;&lt;/svg&gt;&lt;/div&gt;</code>) without the red circle.</p>
  <p>A possible explanation is that <code>React.useEffect</code> <a href="https://stackoverflow.com/a/65638562/5599687">does not run on server</a>. However, I do not understand why this does not run <em>after</em> the Javascript is loaded. In any case, I cannot find how to work around this problem, so any help to understand it better or a solution will be appreciated :)</p>
  <hr />
  <p>I list my relevant code below. I am rather new with Node, so I tried to stick to Express example conventions.</p>
  <h3>app.js</h3>
  <pre><code>var simulationRouter = require('./routes/simulation');
  var app = express();
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'jsx');
  app.engine('jsx', require('express-react-views').createEngine());
  ...
  app.use('/simulation', simulationRouter);
  </code></pre>
  <h3>routes/simulation.js</h3>
  <pre><code>var express = require('express');
  var router = express.Router();
  
  router.get('/', function(req, res, next) {
    res.render('d3_show_nolib');
  });
  
  module.exports = router;
  </code></pre>
  <h3>views/d3_show_nolib.js</h3>
  <pre><code>import React, { useEffect, useRef } from &quot;react&quot;;
  import { select } from &quot;d3&quot;;
  
  export default function App() {
    const svgRef = useRef();
    useEffect(() =&gt; {
      const svg = select(svgRef.current);
      const getData = () =&gt; {
        svg
          .append(&quot;circle&quot;)
          .attr(&quot;r&quot;, 15)
          .attr(&quot;fill&quot;, &quot;red&quot;)
          .attr(&quot;stroke&quot;, 1.5);
      };
      getData();
    }, []);
  
    return (
      &lt;div&gt;
        &lt;p&gt;D3 Exemple&lt;/p&gt;
        &lt;svg ref={svgRef}&gt;&lt;/svg&gt;
      &lt;/div&gt;
    );
  }
  </code></pre>
  <p>(I expect this to work as the following single html file:</p>
  <pre><code>&lt;html&gt;
    &lt;head&gt;
      &lt;script src=&quot;https://d3js.org/d3.v7.min.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
  
      &lt;svg id='svg'&gt;&lt;/svg&gt;
  
      &lt;script&gt;
        var svg = d3.select('#svg');
  
        svg.attr('width', 100)
           .attr('height', 100);
        svg
          .append(&quot;circle&quot;)
          .attr(&quot;r&quot;, 15)
          .attr(&quot;fill&quot;, &quot;red&quot;)
          .attr(&quot;stroke&quot;, 1.5)
          .attr('cx', 10)
          .attr('cy', 10);
      &lt;/script&gt;
  
    &lt;/body&gt;
  
  
  &lt;/html&gt;
  </code></pre>
  <p>)</p>