I want to refactor an existing React app and add styled-components
.
The issue is that the only way I'm seeing this working is if I rename all existing functional components, create new styled ones, and name them with the old names, so that when I use them to build the App, it looks the same.
I renamed this component from Button
to DefaultButton
:
class DefaultButton extends React.Component {
render() {
return <button className={this.props.className}>
{this.props.text}
</button>;
}
}
And then created the styled component with the old name:
let Button = styled(DefaultButton)`
color: ${props => props.theme.buttonStyles.color};
background-color: ${props => props.theme.buttonStyles.backgroundColor};
`;
Button.defaultProps = {
theme: {
buttonStyles: {
color: '#000',
backgroundColor: '#ccc'
}
}
};
export default Button;
And now I can use it as before:
<ThemeProvider theme={mytheme}>
<div className="App">
<Button text="Give me an answer here"></Button>
</div>
</ThemeProvider>
Is there a way to add the new styles and not rename all existing components? Any improvement/advice to the code above is welcomed.
Thank you!
You do not need to rename the components, you can simply write it like
class Button extends React.Component {
render() {
return <button className={this.props.className}>
{this.props.text}
</button>;
}
}
Button = styled(Button)`
color: ${props => props.theme.buttonStyles.color};
background-color: ${props => props.theme.buttonStyles.backgroundColor};
`;
Button.defaultProps = {
theme: {
buttonStyles: {
color: '#000',
backgroundColor: '#ccc'
}
}
};
export default Button;