'How to use React.forwardRef with typescript
I want to write a component with props using forwardRef, like:
const Greeting = React
.forwardRef<
HTMLDivElement,
{name: string}>(
(props, ref) => <div ref={ref}>{`Hello ${props.name}`}</div>,
);
However, I got a error message.
TS2339: Property 'name' does not exist on type '{ children?: ReactNode; }'.
Configuration:
// webpack.config.js
module.rules=[{
test: /.tsx?$/,
exclude: /node_modules/,
use: [
'ts-loader',
{
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],
plugins: [
[
/**
* To suppost material ui's styled components selector
*/
'@emotion',
{
importMap: {
'@mui/system': {
styled: {
canonicalImport: ['@emotion/styled', 'default'],
styledBaseImport: ['@mui/system', 'styled'],
},
},
'@mui/material/styles': {
styled: {
canonicalImport: ['@emotion/styled', 'default'],
styledBaseImport: ['@mui/material/styles', 'styled'],
},
},
},
},
],
],
},
},
],
},]
// tsconfig.json
{
"compilerOptions": {
"esModuleInterop": true,
"sourceMap": true,
"jsx": "react",
"noEmitOnError": true,
}
}
Is there some way to create a component with props and ref using typescript?
d.ts source code in React follow:
function forwardRef<T, P = {}>(render: ForwardRefRenderFunction<T, P>): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;
interface ForwardRefRenderFunction<T, P = {}> {
(props: PropsWithChildren<P>, ref: ForwardedRef<T>): ReactElement | null;
displayName?: string | undefined;
// explicit rejected with `never` required due to
// https://github.com/microsoft/TypeScript/issues/36826
/**
* defaultProps are not supported on render functions
*/
defaultProps?: never | undefined;
/**
* propTypes are not supported on render functions
*/
propTypes?: never | undefined;
}
type PropsWithChildren<P> = P & { children?: ReactNode | undefined };
I think it just add a children properties filed to my type. But why it eventually removes all the types define, remaining only the children?
Solution 1:[1]
const Greeting = React
.forwardRef<
HTMLDivElement,
{name: string}>(
(props, ref) => <div ref={ref}>{`Hello ${props.name}`}</div>,
);
Your prop should be type like that:
{name}: {name: string}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | adscud |
