Ronze
Ronze

Reputation: 1574

SVG viewbox error with React

I cannot for the life of me figure out what's going wrong here. I have the following component:

import React, { Component } from 'react';

class MySvg extends Component {
  render() {
    return (
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {this.props.width} {this.props.height}"></svg>
    );
  }
}

export default MySvg;

When I try to render the component, I get the following error:

Error: <svg> attribute viewBox: Expected number, "0 0 {this.props.widt…"...

I am 100% sure that both props are numbers. They have a typeof number when I console.log, and they are passed as numbers. Is this a problem with React?

Upvotes: 1

Views: 10945

Answers (2)

ochayon
ochayon

Reputation: 41

You can also use string interpolation to solve this in a more readable way:

<svg xmlns="http://www.w3.org/2000/svg" viewBox=`0 0 ${this.props.width} ${this.props.height}`></svg>

Upvotes: 4

Tharaka Wijebandara
Tharaka Wijebandara

Reputation: 8065

The problem is your props are inside the string and it doesn't evaluate and get assigned because of that. Use something like this instead.

<svg xmlns="http://www.w3.org/2000/svg" viewBox={"0 0 "+ this.props.width + " " + this.props.height}></svg>

In this way, we basically create the value by concatenating props and strings inside the brackets. Because inside the brackets it is all JavaScript.

Upvotes: 4

Related Questions