0

I am trying to use the browsers native tooling for creating svg elements within a react component. The error I get when creating an element and placing that variable in the render method is the following:

Objects are not valid as a React child (found: [object Element])

I can get the element to the page with the following but I know it is not the best way. What would be the proper way for handling this case?

import React from 'react'


export default class Circle extends React.Component {

  componentDidMount() {
    let canvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
    canvas.appendChild(document.createElementNS('http://www.w3.org/2000/svg', 'ellipse'))
    document.getElementById('element').appendChild(canvas)
  }

  render() {
    return (
      <div id='element'></div>
    );
  }
}

2 Answers 2

3

You can simply use svg and ellipse tag in your code.

And here is all supported svg attributes.

import React from 'react'

export default class Circle extends React.Component {

  render() {
    return (
      <div id='element'>
          <svg></svg>
          <ellipse></ellipse>
      </div>
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

React's SVG support is (almost) at feature parity. The error that you got was likely using a javascript object that wasn't a React component. For example, something like this is completely valid:

class CaretIcon extends React.Component {
  render() {
        return (
         <svg
          xmlns="http://www.w3.org/2000/svg"
          xmlnsXlink="http://www.w3.org/1999/xlink"
          height={100}
          style={{ enableBackground: 'new 0 0 512 512'}}
          version="1.1"
          viewBox="0 0 512 512"
          width={100}
          xmlSpace="preserve">
            <path d="M413.1,327.3l-1.8-2.1l-136-156.5c-4.6-5.3-11.5-8.6-19.2-8.6c-7.7,0-14.6,3.4-19.2,8.6L101,324.9l-2.3,2.6  C97,330,96,333,96,336.2c0,8.7,7.4,15.8,16.6,15.8v0h286.8v0c9.2,0,16.6-7.1,16.6-15.8C416,332.9,414.9,329.8,413.1,327.3z"/>
        </svg>
    )
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.