Add a class= attribute to an <svg> that is already defined

Viewed 119

Let's say I have icons:

//myicons.js
import React from "react";

export const ico = {
    someIcon:
        <svg ... >
           ...
        </svg>,

And a component that uses some icon:

import React, { Component } from "react";
import { ico } from "./myicons";

export class MyIcon extends Component {
    render () {
        return ico[this.props.which];
    }
}

And somewhere that uses the icon:

//some render func
return (
    <div ... >
        <MyIcon which="someIcon"/>
        ...
    </div>
);

Suppose I were to add a css class:

<MyIcon which="someIcon" className="blahblah" />

..how do I get the DOM to end up containing <svg class="blahblah" i.e. how do I add the blahblah class given in <MyIcon className="blahblah" to the class= attribute of the <svg returned by ico[this.props.which] ?

If it helps, this is what ends up being returned from the render:

enter image description here

1 Answers

I would write it like this:

import React from "react";

const getIconWithClass = (type, className) => {
  switch (type) {
    case "iconA":
      return <svg className={className}>iconA</svg>;
    case "iconB":
      return <svg className={className}>iconB</svg>;
    default:
      return null;
  }
};
class MyIcon extends React.Component {
  render() {
    const { which, className } = this.props;
    return getIconWithClass(which, className);
  }
}

const App = () => {
  return (
    <div>
      <MyIcon which="iconA" className="bla-bla" />
    </div>
  );
};

export default App;
Related