hairyhendrix
hairyhendrix

Reputation: 31

Typescript - Rendering Connected Components

Using TypeScript and React/Redux, I have typed a ConnectedComponent. But when I try to render that component, TypeScript is throwing an error saying that the required props aren't passed.

Ex.

interface Props extends MapStateProps {

}

class App extends React.Component<Props, {}> {
  render(): JSX.Element {
    return (
      <>
        <Router>
          <Switch>
            <Route path="/" component={Dashboard} />
          </Switch>
        </Router>
      </>
    );
  }
}

interface MapStateProps {
  user: UserState;
}

const MapStateToProps = (state: AppState): MapStateProps => ({
  user: state.user,
});

const connectedApp = connect(MapStateToProps, null)(App);

export {
  connectedApp as App,
};

Then when I render the component like:

<App />

It says that App requires the 'user' prop. How can I do this without setting the user prop as optional?

Upvotes: 2

Views: 200

Answers (3)

zakaria amine
zakaria amine

Reputation: 3682

Here is what worked for me:

//...

const connectedApp = connect(MapStateToProps, null)(App);

export default connectedApp ;
export { connectedApp as App};

Upvotes: 0

gautamits
gautamits

Reputation: 1292

Please try this and see if it helps.

interface UserState{}
interface AppState{
  user: UserState;
}
interface MapStateProps {
  user: UserState;
}
interface Props extends MapStateProps {}

class App2 extends React.Component<Props, {}> {
  render(): JSX.Element {
    return (
      <div>
          App2
      </div>
    );
  }
}

const MapStateToProps = (state: AppState): MapStateProps => ({
  user: state.user,
});

export default connect(MapStateToProps, null)(App2);

Upvotes: 1

Francesc Montserrat
Francesc Montserrat

Reputation: 349

Replacing

export {
  connectedApp as App,
};

With the default export:

export default connectedApp;

And then the import

import {App} from './App';

For

import App from './App';

Upvotes: 0

Related Questions