0

I have a menuItem component and its props is a Icon component created by me and called FontIcon.

And in menuItem props you can pass a name of the icon as a string, for example: leftIcon="face" but you can also pass a code for the component like this: leftIcon='<FontIcon style={{color:"red"}} className="face" />'.

In the first case, all works perfectly, the props is passed to the variable where is code for the component:

leftIcon = <FontIcon size={_props.fontSize} className={_props.leftIcon} />;

But this second way is not working. When the user passes all code I need to add something to this(this size value like above), at this point this adding works:

leftIcon = _props.leftIcon.replace(/\/>$/, " size={_props.fontSize}/>");

Here I've got if to check what has the user passed:

if (_props.leftIcon.match(/<.+\/>/)) {
    leftIcon = _props.leftIcon.replace(/\/>$/, " size={_props.fontSize}/>");
} else {
    leftIcon = <FontIcon size={_props.fontSize} className={_props.leftIcon} />;
}

But in this second way, I'm getting a string and it doesn't work. There is no icon, but there is a string with code:

enter image description here

So I've consoled log this and it's what I got:

enter image description here

The typeof this first is object but this second one is string.

So what can do to make this second way works?

Karol
  • 447
  • 1
  • 7
  • 16

2 Answers2

0

If this code is in the render portion this should work;

if (_props.leftIcon.match(/<.+\/>/)) {
    leftIcon = _props.leftIcon.replace(/\/>$/, " size={_props.fontSize}/>");
} else {
    leftIcon = (<FontIcon size={_props.fontSize} className={_props.leftIcon} />);
}

Note the parenthesis.

J. Mark Stevens
  • 4,911
  • 2
  • 13
  • 18
0

There's a way to create component from string you can take a look on this answer

But I would suggest you to pass styles and / or class names and other parameters to your component rather then a string and then you could just have:

 return <FontIcon class={condition ? 'firstClass' : 'secondClass'} ... />;
Community
  • 1
  • 1
Ivan Leonenko
  • 2,363
  • 2
  • 27
  • 37