Reputation: 3559
I have a react class with some div and I want to add some extra HTML from a function.
When I run this I get an error saying that OverlayButton is not defined. My inspiration is from HERE
I know that I can split the OverlayButton out in a separate class, but it is just a dumb button with no logic.
export default class Widget extends React.Component {
OverlayButton(props) {
return (
<div
className={props.className}
onClick={props.handler}
ref='select'>
<i className="material-icons">
{props.icon}
</i>
</div>
)
}
render() {
return (
<div>
<div className="photo-widget-content"></div>
<div className="photo-widget-header"></div>
<img src={this.props.photo.url}></img>
return <OverlayButton icon="check" handler="" className=""/>
</div>
);
}
}
Upvotes: 3
Views: 94
Reputation: 20027
You're almost there, just replace <OverlayButton ... />
with <this.OverlayButton ... />
Strictly speaking, in response to the other answer (which is also correct), there is no need to call it as a function, since you could rely on JSX to do it for you.
Here an example.
class Widget extends React.Component {
OverlayButton(props) {
return (
<div>
Button
</div>
);
}
render() {
return (
<div>
<this.OverlayButton />
</div>
);
}
}
ReactDOM.render(
<Widget />,
document.getElementById('container')
);
With that being said, I'd probably wouldn't define OverlayButton
as an instance method of a class, but rather move it on top of the class and simply define it as a function... something like this:
const OverlayButton = (props)=> {
return (
<div>
Button
</div>
);
}
and then
class Widget extends React.Component {
...
render() {
return <OverlayButton ... />
}
}
Upvotes: 3
Reputation: 193261
If you want to use OverlayButton as a function (method) you need to call it inside {}
braces:
export default class Widget extends React.Component {
OverlayButton(props) {
return (
<div
className={props.className}
onClick={props.handler}
ref='select'>
<i className="material-icons">
{props.icon}
</i>
</div>
)
}
render() {
return (
<div>
<div className="photo-widget-content"></div>
<div className="photo-widget-header"></div>
<img src={this.props.photo.url} />
{this.OverlayButton({
icon: 'check',
handler: function() {},
className: ''
})}
</div>
);
}
}
Upvotes: 2