Search code examples
javascriptreactjstypescripttsxreact-tsx

Importing Components with React/TypeScript


I want to import Test component into Home but I keep getting the following error:

Module '"/.../src/components/Test"' has no default export. Did you mean to use 'import { Test } from "/.../src/components/Test"' instead?

In the test component I keep getting the following error on exporting Test:

Type '({ name }: Props) => void' is not assignable to type 'FC<Props>'.
  Type 'void' is not assignable to type 'ReactElement<any, any> | null'

Test component

import React,{FC} from 'react';

interface Props {
  name: string;
}
export const Test:FC<Props> = ({ name }: Props) => {
  <div>{name}</div>
};

Home component

import React from 'react';
import Test from './Test'

export const Home = () => {
  <div><Test name="example" /></div>
};

tsconfig.json

{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": ["src"]
}

Solution

  • Your code is incorrect. The error has to do with how ES6 arrow functions (or ES Modules) work.

    So allow me to explain: you're geting a TypeScript error because your Test component doesn't actually return the JSX you're creating.

    export const Test:FC<Props> = ({ name }: Props) => (
      <div>{name}</div>
    );

    If you were to replace the curly braces with parens, your code works fine.

    Furthermore, named exports are not equal to default export. In your example, you're exporting Test via export const Test and not default.

    As you have not exported a default, import Test from './test.tsx' won't work.

    I suggest you read up on ES Modules, and ES6 arrow functions.