I'm trying to wrap material-ui button into another component. Everything goes fine unless I've tried to handle onClick event. It seems that it works only once.
(not) Working example available at:
https://codesandbox.io/embed/material-demo-nn0ut?fontsize=14
Source code:
import React from "react";
import { useState } from "react";
import MaterialButton from "@material-ui/core/Button";
import { Component } from "react";
import { withStyles } from "@material-ui/core";
const stylesMain = {
root: {
fontSize: 16
}
};
const stylesSecondary = {
root: {
fontSize: 14
}
};
const StyledButtonMain = withStyles(stylesMain)(MaterialButton);
const StyledButtonSecondary = withStyles(stylesSecondary)(MaterialButton);
class Button extends Component {
constructor(props) {
super(props);
this.onClick = function() {};
this.href = null;
this.target = null;
this.type = "button";
if (props.onClick) {
this.onClick = props.onClick;
}
if (props.href) {
this.href = props.href;
}
if (props.target) {
this.target = props.target;
}
if (props.type) {
this.type = props.type;
}
}
render() {
const StyledButton =
this.props.color === "secondary"
? StyledButtonSecondary
: StyledButtonMain;
return (
<StyledButton
type={this.type}
href={this.href}
target={this.target}
onClick={this.onClick}
variant="contained"
style={{ whiteSpace: "nowrap" }}
>
{this.props.children}
</StyledButton>
);
}
}
export default function Counter(props) {
const [counter, setCounter] = useState(0);
return (
<div>
<h1>Counter: {counter}</h1>
<Button
onClick={() => {
setCounter(counter + 1);
}}
>
ClickMe
</Button>
</div>
);
}
I've expected, that onClick should work in the same manner as in "bare" material ui button. How can I fix that?
Your issue is that you're binding the onClick
function in the Button
constructor. As you may know, the constructor function is only called once, whenever an instance of the Button
class is created.
In your case, you're basically binding the setCounter
function with a fixed value of 1 right in the constructor and from that point on, you ignore the function values passed in the onClick
prop.
To fix this, all you need to do is replace the following line in the Button
render function:
onClick={this.onClick}
With this one:
onClick={this.props.onClick}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments