Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript + React + Emotion: typesafe ref forwarding when using `as`

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?

like image 316
corvid Avatar asked Apr 20 '26 06:04

corvid


1 Answers

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} />;
});
like image 162
astrix Avatar answered Apr 21 '26 20:04

astrix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!