Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - exporting multiple classes in the same file

I am working on a project in react where I have multiple components. I am trying to do it all in JSBin (lol.. I know). But i am having issues with exporting multiple classes.

class Foo extends React.Component {
    constructor(props) {
        super(props);

        this.state = {

        }
    }

    render() {
        return (
            <div></div>
        );
    }
}


class Bar extends React.Component {
    constructor(props) {
        super(props);

        this.state = {

        }
    }

    render() {
        return (
            <div></div>
        );
    }
}

export class Foo{};
export class Bar{};

But I am getting an error of

  Parsing error: Identifier 'Foo' has already been declared
  92 | }
  93 | 
> 94 | export class Foo{};
     |              ^
  95 | export class Bar{};

So then I tried to change it to this

class Foo extends React.Component {...my code}
class Bar extends React.Component {...my code}

and it compiles but I get an runtime error of

Error: Element type is invalid: expected a string (for built-in components) or a class/function       (for composite components) but got: object.

Is it possible to export multiple classes in a single file with react?

like image 270
eskimo_amigo Avatar asked Oct 12 '25 12:10

eskimo_amigo


1 Answers

It's because you are re-declaring the class at the bottom, you can export your classes like the following.

export class Foo extends React.Component {
   // your code
}

export class Bar extends React.Component {
  // your code
}
like image 134
TenTen Peter Avatar answered Oct 14 '25 01:10

TenTen Peter



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!