skip to Main Content

I have two files for my component:

  • app/components/SomeButton.ts

  • app/components/SomeButton.tsx

The .ts contains most of the logic/code and the .tsx extends the .ts and contains just the render function.

When I want to import the .tsx in some other file (e.g. App.tsx) like this:

import SomeButton from 'app/components/SomeButton';

it tries to import the .ts file instead.

Is there a way to force it to load the .tsx file instead?

A workaround would be to use 2 different names but having te same name would be a bit cleaner.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to the comment of @DomA I now ended up with this pretty satisfactory construction (though not a perfect answer to the question):

    app/components/SomeButton.ts:

    import React from 'react';
    
    export abstract class SomeButton extends React.Component<{},{}> {
    
        protected label:string;
    
        constructor(props) {
            super(props);
    
            this.label = 'Some Button';
        }
    
        public componentDidMount():void {
            tr('Some Button mounted');
        }
    
        // ... more code and handlers here..
    
    }
    

    app/components/SomeButton.r.tsx: (the r is arbitrary)

    import { SomeButton as Component } from './SomeButton';
    
    export default class SomeButton extends Component {
    
        public render() {
            return (
                <>
                    <button>{this.label}</button>
                </>
            );
        }
    }
    

    You can now import the component wherever you like like this: import SomeButton from 'app/components/SomeButton.r';

    import SomeButton from 'app/components/SomeButton.r';
    

  2. Why not simply add the desired extension to your import:

    import SomeButton from 'app/components/SomeButton.tsx';
    

    Although, if I were to split a component into multiple files, I would probably create a folder for that component and keep all the files in there. You could have:

    └── components
        └── SomeButton
            ├── SomeButton.ts
            ├── SomeButton.tsx
            └── SomeButton.css
    
    

    That way, you’re original objective could be accomplished by adding an index.js that exports the tsx component as default:

    import SomeButton from './SomeButton.tsx';
    
    export default SomeButton;
    
    //Your original line of code would now import 'SomeButton.tsx':
    import SomeButton from 'app/components/SomeButton';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search