eskimo_amigo
eskimo_amigo

Reputation: 41

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?

Upvotes: 4

Views: 958

Answers (3)

SAKSHI GOYAL
SAKSHI GOYAL

Reputation: 87

You can also do:

export Foo;

export Bar;

in the end instead of declaring the class again.

Upvotes: 0

junwen-k
junwen-k

Reputation: 3644

You can declare your classes as usual, then export all your classes at the end of the file as the following

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 { Foo, Bar };

Or if you prefer, you can export the class as you declare them.

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

    this.state = {};
  }

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

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

    this.state = {};
  }

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

Generally its suggested that only export one component per file as per es-lint's rule.

Upvotes: 1

Junius L
Junius L

Reputation: 16132

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
}

Upvotes: 3

Related Questions