5

I’m trying to create a chart reusable component, but I can’t wrap my brain around it.

The idea is to reuse the following SVG using react (let’s call it “Axes”), together with some functionality and state like width and height, data→coordinate mapping and so on:

<svg width={...} height={...}>
    <g ref="area" transform={...}>
        {chartElements}
    </g>
    <g ref="xAxis">...</g>
    <g ref="yAxis">...</g>
</svg>

Then I’d use this SVG and state for multiple chart components.

The ways to do it could be

  1. Make Axes a component, use this.props.children instead of chartElements, and define a Chart component like so:

    render: function() {
        return (
            <Axes ref="axes" {...this.props}>
            {this.props.data.map(function(d) {
                return <rect x={this.refs.axes.state.xMap(d)} />
            })}
            </Axes>
        )
    }
    

    But this would need access to Axes’ props and state which we can’t get this way during rendering.

  2. Wrap the functionality in a mixin, and change the render method into a wrapAxes(chartElements) method of the mixin, which returns above snippet.

    This would intermingle the state of the Axes and the chart, and need special attention, as each chart needs to call wrapAxes on its return value

  3. Pass a component as prop, which would then get passed the state/props on render? Is this even possible?

  4. ???

I just don’t know how to approach this.

flying sheep
  • 8,475
  • 5
  • 56
  • 73
  • What does the data source look like? Is it getting set once? When is it being set? Is the data changing over time? – Brett DeWoody Dec 31 '14 at 17:17
  • the data is a prop of the chart: See `this.props.data` in the code – flying sheep Jan 01 '15 at 23:12
  • I don't see a parent child relation between the axes and the content you require. Might be easier to make axes a mixin with a renderAxes function and other as you desire. And in the data component call this.renderAxes() as required with params if needed. – amankapur91 Mar 13 '15 at 21:49
  • Please give us a concrete example of the SVG in order to help us better understand the context of the question. – Cristik Apr 23 '15 at 07:47

1 Answers1

0

I am using d3 along with React to do this, but this code might answer your question

Amey
  • 2,214
  • 2
  • 19
  • 28