I am a trying to make a component which gets passed to react-redux's connect
function.
The component is as follows:
interface ITestProps {
id: number
}
class TestComponent extends React.Component<ITestProps, {}> {
render() {
return (<div>
{this.props.name}
</div>)
}
}
mapStateToProps(state) {}
mapDispatchToProps(dispatch) {}
let ConnectedComponent = connect(
mapStateToProps,
mapDispatchToProps
)(TestComponent)
The above code seems to work find if i render ConnectedComponent
like so
<ConnectedComponent></ConnectedComponent>
i.e without the id
prop. Shouldn't it throw an error since the ConnectedComponent
is simply the connected form of TestComponent
and TestComponent
should have props of the form ITestProps
.
Is this how it is supposed to behave or am I doing something wrong.
We strongly recommend using TypeScript in Redux applications. However, like all tools, TypeScript has tradeoffs. It adds complexity in terms of writing additional code, understanding TS syntax, and building the application.
Better support for JSX Another additional benefit of TypeScript + React is that it provides better IntelliSense, code completion for JSX. Tip: Share your reusable components between projects using Bit (Github). Bit makes it simple to share, document, and reuse independent components between projects.
We recommend using the React-Redux hooks API as the default approach in your React components. The existing connect API still works and will continue to be supported, but the hooks API is simpler and works better with TypeScript. These hooks were first added in v7.1.0.
I'm not sure why the typings can't infer the type from the presentational component alone, but it will work if ownProps is typed in connect ->
let ConnectedComponent = connect<{}, {}, ITestProps>(
mapStateToProps,
mapDispatchToProps
)(TestComponent)
It also can infer it if ownProps is typed in mapDispatchToProps ->
mapStateToProps(state, ownProps: ITestProps) {}
Include a constructor inside the class like this:
constructor(props) {
super(props)
}
Without the constructor the props don't get loaded
Instead of
let ConnectedComponent = connect(
mapStateToProps,
mapDispatchToProps
)(TestComponent)
I added (obviously mapStateToProps
& mapDispatchToProps
have to be defined before the connect function)
@connect(mapStateToProps, mapDispatchToProps)
above
class TestComponent extends React.Component<ITestProps, {}> {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With