I am using emotion and typescript. I have a component which (roughly) looks as follows
import styled from '@emotion/styled';
export default Box = styled.div`
display: flex;
align-items: center;
justify-content: center;
`;
In another component, I am using that div but using the as prop to make it into a button.
However, when I forward the ref, I want to appropriately type it to be the type of whatever that element is. i.e.,
import React, { forwardRef } from 'react';
import Box from '../Box';
const Button = forwardRef((props, ref) => {
return <Box {...props} as="button" ref={ref} />;
});
If I took this one step further, ideally as could be anything that is accepted by styled.div() and know what the type of ref would be.
However, I can't find the appropriate way to type ref in a way that matches as expected.
How would this be done?
You can try something like:
interface ButtonProps = {
props: {}
}
const Button = forwardRef(({ ...props }: ButtonProps, ref?: React.Ref<HTMLButtonElement & HTMLAnchorElement>) => {
return <Box {...props} as="button" ref={ref} />;
});
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