javascriptstringstring-formattingnivo-react

Nivo ResponsiveLineCanvas axis multiline format


Having read @nivo docs and SO threads I've found no solution of my problem which is multi-line format of x-axis values.

I need to see date like this

2022.10.02
14:42:30

but is see 2022.10.02 14:42:30

What I tried is

axisBottom={{
  format: value => moment(value).format('DD.MM.YYYY\r\nHH:mm:ss'),
}}                                  

but it gives no effect except space between date part. React component is not acceptable for rendering, callback function must return value only of string type.

So the question is there a way to create multi-line string?

(image below illustrates current output)

this is how it looks now


Solution

  • Text, which is returned from format method, is set to <text> tag as a string and doesn't wrap words. We need to split symbols that we need to place in different lines by putting them into tags. The only tag, which could help us here, is <tspan>.

    const formatAxisBottom = value => {
      const str = moment(value).format('DD.MM.YYYY HH:mm:ss'),
      const strArr = str.split(" "); // array of 2 
      
      return (
        <>
          {strArr.map(line => <tspan x="0" dy="1em">{line}</tspan>)} 
        </>
      )};
    
    //...you bar props...
    axisBottom={{
      format: formatAxisBottom,
    }}
    

    dy - shift along the y-axis, it's needed to place lines in column. I'd recommend to set the value = font-size value of tspan;

    x-"0" - place lines aligned center