Code example: https://codesandbox.io/s/confident-shadow-o84fn
So I have a super stripped back and basic version of my issue on the link above.
Essentially - I have an un-styled TextInput component that I am unable to modify, but have been told I need to use. I have created my own higher order component that takes in the default input and modifies it to my liking. I have added several new props, supporting text etc that builds on top of the default.
Everything works as expected, However, I'm unable to style the component I'm passing with Styled Components as I would expect to.
<Container /> and <SupportingCopy /> are both styled as I'd like (As they're new elements). However, unless I add a generic input style inside my Container I can't seem to achieve what I need.
I've tried adding something similar to const NewStyledInput = styled(TextInput) inside my StyledInput, but then I'm faced with render issues.
What would be the best way to style <TextInput /> as I have the rest of the component?
In my example - I'd like to turn the border of my input green when isFocused is true (As it does the supporting text). I appreciate this seems quite minor - But I've stripped quite a lot out of this example to make it simpler to explain.
Thanks for any help!
const withStyles = TextInput => {
const StyledInput = ({ ...props }) => {
const { onFocusCallback, onBlurCallback } = props;
const [isFocused, setIsFocused] = useState(false);
const handleFocusBlur = () => {
setIsFocused(!isFocused);
};
return (
<Container>
// I want to style TextInput with Styled Components.
<TextInput
{...props}
onFocusCallback={handleFocusBlur}
onBlurCallback={handleFocusBlur}
isFocused={isFocused}
/>
<br />
<SupportingCopy isFocused={isFocused}>
Some additional text
</SupportingCopy>
</Container>
);
};
I'm not sure why you need HOC in this situation, so it's pretty straight forward:
const Container = styled.div`
position: relative;
`;
const SupportingCopy = styled.label`
color: ${({ isFocused }) => (isFocused ? 'green' : 'inherit')};
font-size: 10px;
`;
const greenBorder = css`
border: 5px solid green;
`;
const MyNewStyledInput = styled(TextInput)`
padding: 10px;
${({ isFocused }) => isFocused && greenBorder};
`;
const StyledInput = props => {
const [isFocused, setIsFocused] = useState(false);
const onFocusCallback = useCallback(() => setIsFocused(p => !p), []);
return (
<Container>
<MyNewStyledInput
{...props}
isFocused={isFocused}
onFocusCallback={onFocusCallback}
/>
<br />
<SupportingCopy isFocused={isFocused}>
Some additional text
</SupportingCopy>
</Container>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With