I have this a component Foo.js
:
// a svg component with a star.svg icon
import { IconStar } from 'react-svg-icons';
// call a button with a custom icon
<Button icon={ IconStar }> Click to trigger </Button>
And then on button.js
I have:
render() {
const theIcon = this.props.icon;
return (
<button>
{this.props children}
{icon() /*this works but i can't pass props inside it*/}
<theIcon className={ Styles.buttonIcon } />
</button>
)
}
I want to render <IconStar>
inside <Button>
, how do I do that?.
I can't pass this as this.prop.children
because it has more logic around the icon prop, but in this case I'm showing only a demo.
Thanks
I have this a component Foo.js
:
// a svg component with a star.svg icon
import { IconStar } from 'react-svg-icons';
// call a button with a custom icon
<Button icon={ IconStar }> Click to trigger </Button>
And then on button.js
I have:
render() {
const theIcon = this.props.icon;
return (
<button>
{this.props children}
{icon() /*this works but i can't pass props inside it*/}
<theIcon className={ Styles.buttonIcon } />
</button>
)
}
I want to render <IconStar>
inside <Button>
, how do I do that?.
I can't pass this as this.prop.children
because it has more logic around the icon prop, but in this case I'm showing only a demo.
Thanks
Share Improve this question asked Feb 28, 2017 at 14:06 sandrina-psandrina-p 4,1609 gold badges36 silver badges66 bronze badges2 Answers
Reset to default 20The only thing you have missed is that for JSX to transpile to JS custom components should be named starting with a capital letter, e.g. <TheIcon />
, while lowercase letter signifies native DOM elements, e.g. <button />
.:
render() {
const TheIcon = this.props.icon; // note the capital first letter!
return (
<button>
{this.props.children}
<TheIcon className={ Styles.buttonIcon } />
</button>
)
}
https://jsfiddle.net/03h2swkc/3/
If your using es6 then you can use a spread operator to pass the attributes to a below component, I think that might solve your problem:
var MyIcon = (props) => {
return <i {...props}> {
props.className
} < /i>
};
var MyButton = (props) => {
return ( < button > {
props.children
}<MyIcon {...props} />< /
button > );
}
ReactDOM.render( <
MyButton className = 'my-icon'>My Button Text</MyButton> ,
document.getElementById('myComponent')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='myComponent'></div>
so the ...props will pass myProps into IconStar. Obviously you can pass anything you want through.