web: components: Fix re-rendering of Button

This commit is contained in:
Alexey Safronov 2019-09-17 14:19:45 +03:00
parent 279d3598cf
commit 111c976280
3 changed files with 49 additions and 18 deletions

View File

@ -1,5 +1,5 @@
import React from 'react';
import { mount } from 'enzyme';
import { mount, shallow } from 'enzyme';
import Button from '.';
describe('<Button />', () => {
@ -10,4 +10,27 @@ describe('<Button />', () => {
expect(wrapper).toExist();
});
it('not re-render test', () => {
const onClick= () => alert('Button clicked');
const wrapper = shallow(<Button size='base' isDisabled={false} onClick={onClick} label="OK" />).instance();
const shouldUpdate = wrapper.shouldComponentUpdate(wrapper.props);
expect(shouldUpdate).toBe(false);
});
it('re-render test by value', () => {
const onClick= () => alert('Button clicked');
const wrapper = shallow(<Button size='base' isDisabled={false} onClick={onClick} label="OK" />).instance();
const shouldUpdate = wrapper.shouldComponentUpdate({
...wrapper.props,
label: "Cancel"
});
expect(shouldUpdate).toBe(true);
});
});

View File

@ -2,6 +2,7 @@ import React from 'react';
import styled, { css } from 'styled-components';
import PropTypes from 'prop-types';
import Loader from '../loader';
import isEqual from "lodash/isEqual";
const activeCss = css`
background-color: ${props => (props.primary ? '#1F97CA' : '#ECEEF1')};
@ -198,20 +199,27 @@ Icon.defaultProps = {
icon: null
};
const Button = props => {
//console.log("Button render");
const { isLoading, label, primary, size, icon } = props;
return (
<StyledButton {...props}>
{(isLoading || icon) &&
isLoading
? <Loader type="oval" size={size === "big" ? 16 : 14} color={primary ? "#FFFFFF" : '#333333'} className="loader" />
: <Icon {...props} />
}
{label}
</StyledButton>
);
};
class Button extends React.Component {
shouldComponentUpdate(nextProps) {
return !isEqual(this.props, nextProps);
}
render() {
// console.log("Button render");
const { isLoading, label, primary, size, icon } = this.props;
return (
<StyledButton {...this.props}>
{(isLoading || icon) &&
isLoading
? <Loader type="oval" size={size === "big" ? 16 : 14} color={primary ? "#FFFFFF" : '#333333'} className="loader" />
: <Icon {...this.props} />
}
{label}
</StyledButton>
);
}
}
Button.propTypes = {
label: PropTypes.string,

View File

@ -22,17 +22,17 @@ const LoginForm = props => {
return onSubmit(event, { login, password });
return false;
}, []);
}, [login, password]);
const onLoginChange = useCallback(event => {
setLogin(event.target.value);
setLoginValid(true);
}, [])
}, [login])
const onPasswordChange = useCallback(event => {
setPassword(event.target.value);
setPasswordValid(true);
}, []);
}, [password]);
return (
<Container>