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
Make Axes a component, use
this.props.children
instead ofchartElements
, 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.
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
Pass a component as prop, which would then get passed the state/props on render? Is this even possible?
???
I just don’t know how to approach this.
I am using d3 along with React to do this, but this code might answer your question