Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React SVG, issue with combining SVG's

If I want to combine multiple SVG parts into a single component, the issue is that every React component has to return a single parent element.

class ComponentA extends Component {
  render() {
    return (

      <svg>
        <Part1 />
        <Part2 />

      </svg>
    )
  }
}


class Part1 extends Component {
  render() {
    return (
      <defs>
        <linearGradient...>
        <etc...>
      </defs>
      <g>
        <path...>
        <text...>
      </g>
)
  }
}


class Part2 extends Component {
  render() {
    return (
      <defs>
        <linearGradient...>
        <etc...>
      </defs>
      <g>
        <circle...>
        <path...>
        <path...>
      </g>
)
  }
}

As we can see, in order to combine multiple SVG components into one component, we have to return both defs and g tags, and possibly also title and maybe others. This breaks the React rule that every component needs to return only one parent element. How do we solve this?

like image 876
Ska Avatar asked Apr 30 '26 20:04

Ska


1 Answers

Use React 16 or wrap defs and g with svg tag, like this:

class Part1 extends Component {
  render() {
    return (
     <svg>
      <defs>
        <linearGradient...>
        <etc...>
      </defs>
      <g>
        <path...>
        <text...>
      </g>
    </svg>
    )
  }
}
like image 173
Tiago Alves Avatar answered May 02 '26 09:05

Tiago Alves