'Getting VS Code to detect React props properly when Redux state props are mixed in
There is a nice example in the React-Redux documentation on how to build a functional component that will receive both props from Redux and from its parent component:
Here is the code from that example. Mind you, I renamed the component MyComponent2 since I already had one called MyComponent:
import * as React from 'react'
import { connect } from 'react-redux'
interface StateProps {
isOn: boolean
}
interface DispatchProps {
toggleOn: () => void
}
interface OwnProps {
backgroundColor: string
}
type Props = StateProps & DispatchProps & OwnProps
const mapState = (state: StateProps) => ({
isOn: state.isOn,
})
const mapDispatch = {
toggleOn: () => ({ type: 'TOGGLE_IS_ON' }),
}
const MyComponent2 = (props: Props) => (
<div style={{ backgroundColor: props.backgroundColor }}>
<button onClick={props.toggleOn}>
Toggle is {props.isOn ? 'ON' : 'OFF'}
</button>
</div>
)
// Typical usage: `connect` is called after the component is defined
export default connect<StateProps, DispatchProps, OwnProps>(
mapState,
mapDispatch
)(MyComponent2)
However, when I try to use that component in another one, VS Code is complaining about this component properties:
Is anything wrong with the code or is it VS Code getting confused? And in any case, what would be the proper solution to fix this?
For the sake of completion, here is the code of the parent component. Note that it is a class component and that I am looking for a solution where the child component would also eventually be a class component:
import * as React from 'react'
import { connect } from 'react-redux'
import MyComponent2 from '../MyComponent2'
interface IMyMainComponentProps {
name: string,
color: string
}
interface IMyMainComponentState {
humor: string
};
const mapStateToProps = (state: IMyMainComponentState) => ({
})
const mapDispatchToProps = {
};
@connect(mapStateToProps, mapDispatchToProps)
export class MyMainComponent extends React.Component<IMyMainComponentProps, IMyMainComponentState> {
constructor(props?: IMyMainComponentProps) {
super(props);
this.state = {
humor: 'happy'
}
}
render() {
return(
<div>
<h1>{this.props.name}</h1>
<div>
{this.props.color}
</div>
<div>
<MyComponent2 backgroundColor='white' />
</div>
</div>
);
}
}
UPDATE:
I have MyComponent2 displaying fine on CodeSandbox:
https://codesandbox.io/s/redux-toolkit-class-components-forked-js2e2h?file=/src/App.tsx
So, I really don't know what it different in my VS Code on my computer:
https://codesandbox.io/s/redux-toolkit-class-components-forked-js2e2h?file=/src/App.tsx
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|