5
votes

I have an existing React component that's coded in JSX and I can't convert to Typescript at this time. I'd like to make use of it in a new React application that is being written in Typescript. I cannot figure out if it's possible to import and use the JSX code within the TSX code. Is this possible? How do I do it?

Thanks

The example below gives the error: TS2604:JSX element type 'OldCode' does not have any construct or call signatures.

OldCode.jsx

import React from 'react'

export default React.createClass({
  render() {
    return <div>OldCode</div>
  }
})

NewCode.tsx

import * as React from 'react';
import { OldCode } from './OldCode';

export default class NewCode extends React.Component<any, any> {
  render() {
    return (
      <OldCode/>
    );
  }
}
3
I gave up on using Typescript for this project and never tracked down why @djwwwww's answer didn't work for me. My instinct says it's right, but since I couldn't confirm, I didn't mark it accepted.Jobu
Try this in tsx to import jsx: const NewCode = require('./NewCode').default;cwtuan

3 Answers

1
votes

Trying changing your import statement:

import OldCode from './OldCode';

If you are using webpack you may need to add .jsx to your resolvers too.

0
votes
declare module '*.jsx' {
    var _: React.Component<any, any>;
    export default _;
}

and use it like

import OldCode from './OldCode.jsx';

put this in some file, make sure it's included in tsconfig.json.

and of course, make sure webpack packs them all.

0
votes

Since there's no accepted answer I will link to my question that actually answers how to write a definition file for an existing component (my question is about a component wrapped in a redux connect):

[How do I create a typescript definition file (d.ts) for an existing redux connected (jsx)component?

Hope it helps someone...