React DOM access issues

Hello all,

Having some trouble with accessing the DOM from a function in React. I’m attempting to dynamically create an element with an unique ID and pass the ID to the function so I can access that ID element and insert a chart. However, when I try to getElementById I get a null value.

CodePen

 chart(canvas) {
    console.log(document.getElementById(canvas));
  }

  table() {
    let strategyStrikes = this.state.strategyStrikes;
    let dates = this.state.dates;

    return dates.map((date, i) => {
      return (
        <div id="table" className="table-responsive m-0 p-0">
          <table className="table table-sm table-hover table-striped table-dark m-0 p-0">
            <thead>
              <tr>
                <th colspan="8" className="text-center">
                  {date}
                </th>
              </tr>
              <tr>
                <th colspan="8" className="text-center">
                  STRIKES
                </th>
              </tr>
            </thead>
            <tbody>
              {strategyStrikes.map((item) => {
                if (item.includes(date) && item.length < 80) {
                  return (
                    <tr>
                      <div id={`${item}`}></div>
                      <td className="text-center">{item.replace(date, "")}</td>
                      {this.chart(`${item}`)}
                    </tr>
                  );
                } else {
                  return null;
                }
              })}
            </tbody>
          </table>
        </div>
      );
    });
  }

I think you need to look into react refs:

I don’t think I am completely grasping this but I’m thinking I would put a

<canvas id={item} ref={this.chartRef}/>

In my table() function.

And in a createChart() function I’d have an

chartRef = React.createRef();
const myChartRef = this.chartRef;

new Chart{myChartRef, { etc ...

Thanks for the pointer! It ended up helping a lot.

Got it to work, albeit I ended up just doing one chart instead of many. But I will make the chart dynamic based on selection.

CodePen

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.