Styled Components - Two Different Elements With The Same Styles
I have a Button
component (in React) which can either be a button
or an a
element, depending on if a href
prop is passed to the component. Something similar to below:
const Button = ({ children, href, onClick }) => {
if(href) {
return <a href={href} onClick={onClick}>{children}</a>;
}
return <button type="button" onClick={onClick}>{children}</button>;
};
I previously used Sass to style these components, but am now attempting to move over to styled-components
. However, I have come across an issue where these two elements require the same styles, but the syntax of styled-components
would require me to create to separate variables - styled.button
and styled.a
, with duplicated styles for each.
I was wondering if there was a way of dynamically changing the element used in styled-components
, maybe based on props in the same way one can change individual CSS properties? I have attempted something along the lines of:
const StyledButton = styled((props) => props.href ? 'a' : 'button')`
...
`;
but no luck so far. Any advice would be greatly appreciated.
Answer
Create generic styles that you can reuse
You can extract and pass styles as string args to a styled component.
const buttonStyles = `
color: red;
...
`
const StyledA = styled.a(buttonStyles);
const StyledButton = styled.button(buttonStyles);
If you need some exceptions
import styled, { css } from ‘styled-components’;
const baseInputStyles = css`
padding: 0.5em;
`;
const StyledA = styled.a`
${baseInputStyles}
`;
const StyledButton = styled.button`
${baseInputStyles}
/* make changes as needed*/
`;
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM