I wanted to add text at the top in LineChart in React’s charting library, Recharts, at an arbitrary position.
The challenge was that the parts of Recharts where the text was to be displayed were specified to be displayed in svg.
One of the requirements was that the text should be displayed with a three-point reader when it exceeded a certain length.
With svg, it was not possible to omit text in CSS, so I did my best with JavaScript, but I found out that you can incorporate HTML tags into SVG using foreignObjects.
This section describes the organisation of this.
Displayed as is on LineChart.
Try to display LineChart as it is according to the formula.
and are elements for handling text in svg.
Therefore, if you just want to draw text, this is OK.
It is not suitable for adapting to variable text (only JavaScript is available.)
<LineChart data={data} margin={chartMargin}>
<text
x={15}
y={25}
fill="black"
textAnchor="left"
dominantBaseline="central"
style={{
display: "block",
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
}}
>
<tspan fontSize={16} fontWeight={700}>
{chartTitle}
</tspan>
</text>
<Line
type="linear"
dataKey="count"
stroke="#0096FA"
dot={false}
strokeWidth={2}
/>
</LineChart>
Incorporating HTML into svg using foreignObject.
If you write it in JavaScript, it becomes long and heavy.
When we considered whether we could use CSS, we came to know about foreignObject.
By using it, it is possible to embed HTML in svg.
You can use the Container and ChartTitle defined in styled-component in the foreignObject tag as it is.
<LineChart data={data} margin={chartMargin}>
<foreignObject y={12} width="100%" height="200">
<Container>
<ChartTitle>{chartTitle}</ChartTitle>
</Container>
</foreignObject>
<Line
type="linear"
dataKey="count"
stroke="#0096FA"
dot={false}
strokeWidth={2}
/>
</LineChart>
Summary
In svg, there were a lot of restrictions, and a lot of the things you could do had to be devised, but after learning about foreignObjects, I think the range of things you can do has expanded.
If you don’t understand something, look it up, ask someone, this is very important.