[Solved] convert the following piece of react code to JSX


At first I thought you were mixing up how to use React.createElement, but fundamentally I don’t think that is your issue. The problem arises that Line isn’t a react component that you can create an element from and pass props to. Instead, you need to create a container that you can then render the plot line into.

Here’s an example component that gets some data and returns a container for plot rendering. It uses a couple lifecycle functions to handle the data update and plot creation. componentDidUpdate allows us to issue “side-effects” in response to react state or props updating, in this case, updating the rendered line plot.

class PlotReact extends Component {
  // Set all line plot settings in state
  state = {
    title: {
      visible: true,
      text: "DEF"
    },
    description: {
      visible: true,
      text: "ABC"
    },
    padding: "auto",
    forceFit: true,
    data: [], // <-- define default empty data array!
    xField: "year",
    yField: "value",
    smooth: true
  };

  componentDidMount() {
    // populate state data, this could be passed via prop, fetched, etc...
    this.setState({ data: plotData });
  }

  componentDidUpdate() {
    // state (or props) updated, recompute line and render it
    const linePlot = new Line(document.getElementById("container"), this.state);

    linePlot.render();
  }

  render() {
    // return a container for the line plot to be rendered into
    return <div id="container" />;
  }
}

Edit modest-turing-ze9uu

If I had one suggestion/tweak, it’d be to move the “state” logic (i.e. plot config, settings, data, etc..) out to a parent component and simply expose them as props. The component simplifies to:

PlotReact

class PlotReact extends Component {
  componentDidMount() {
    this.renderPlot();
  }

  componentDidUpdate() {
    this.renderPlot();
  }

  renderPlot() {
    const linePlot = new Line(
      document.getElementById("plot-container"),
      this.props // <-- just getting from props now!
    );

    linePlot.render();
  }

  render() {
    return <div id="plot-container" />;
  }
}

Some Parent

export default function App() {
  const plotConfig = {
    title: {
      visible: true,
      text: "DEF"
    },
    description: {
      visible: true,
      text: "ABC"
    },
    padding: "auto",
    forceFit: true,
    xField: "year",
    yField: "value",
    smooth: true
  };

  // ... some function to fetch/populate plotData

  return (
    <div className="App">
      <PlotReact {...plotConfig} data={plotData}/>
    </div>
  );
}

This allows you to use different plot settings, change them during component lifecycle, and have multiple instantiations with different settings. In other words, it is now reusable as the render logic is decoupled from use cases.

0

solved convert the following piece of react code to JSX