🏠 back to Observable

yield svg.node() in react jsx

Hi. I’m learning D3.js with making it work in React. I made simple bar chart, scatter chart and so on.
Now I have faced a problem with pachinko simulator on my react app. When I run the simulator, ‘yield’ makes an error. How can I apply below observablehq codes in react jsx?

[observablehq codes]

for (let i = 0; i < n; ++i) {
if (i % 5 === 0) yield svg.node();
const cx = x(values[i]);
const cy = height - margin.bottom - dodge(cx) - radius - 1;

svg.append("circle")
    .attr("cx", cx)
    .attr("cy", -400)
    .attr("r", radius)
  .transition()
    .duration(750)
    .ease(d3.easeBounce)
    .attr("cy", cy);

}

yield svg.node();

When Observable compiles a cell’s code, it applies some modifications, like wrapping each cell’s body in a function declaration.

If yield is used inside a cell, then Observable will automatically declare a generator (i.e., function*()).

The code that you referenced gets compiled to:

function*(replay,dodger,radius,n,random,d3,width,DOM,height)
{
  replay;
  const dodge = dodger(radius * 2 + 1);
  const margin = ({top: 0, right: 10, bottom: 20, left: 10});
  const values = Float64Array.from({length: n}, random);
  const x = d3.scaleLinear(d3.extent(values), [margin.left, width - margin.right]).nice();
  const svg = d3.select(DOM.svg(width, height)).style("overflow", "visible");

  svg.append("g")
      .attr("transform", `translate(0,${height - margin.bottom})`)
      .call(d3.axisBottom(x));

  for (let i = 0; i < n; ++i) {
    if (i % 5 === 0) yield svg.node();
    const cx = x(values[i]);
    const cy = height - margin.bottom - dodge(cx) - radius - 1;

    svg.append("circle")
        .attr("cx", cx)
        .attr("cy", -400)
        .attr("r", radius)
      .transition()
        .duration(750)
        .ease(d3.easeBounce)
        .attr("cy", cy);
  }

  yield svg.node();
}

(Source: https://api.observablehq.com/@mbostock/pachinko-simulator.js?v=3)

1 Like

Thank you for the reply. I will try to modify code. (I wish I could have d3.js generator function example in HTML. I searched ‘Bl.ocks.org’ but I couldn’t find it.)