Issue
Currently, I am trying to learn typescript through ionic react by creating simple webpages. I came across this interesting navigation bar but it is written in jsx. Hence, I want to write in tsx with the help of this website.
Code in jsx
import { enquireScreen } from 'enquire-js';
let isMobile;
enquireScreen((b) => {
isMobile = b;
});
class Home extends React.PureComponent {
state = {
isMobile,
}
componentDidMount() {
enquireScreen((b) => {
this.setState({
isMobile: !!b,
});
});
}
How do I write this in typescript? I have tried changing stuff like the declaration of the variable but could not get it to work. Thanks.
Solution
All you really have to do here is add types to your variables.
let isMobile: boolean;
enquireScreen((b: boolean) => {
isMobile = b;
});
export class Home extends React.PureComponent {
state = {
isMobile,
}
componentDidMount() {
enquireScreen((b: boolean) => {
this.setState({
isMobile: !!b,
});
});
}
}
Since the enquire-js
doesn't come with type declarations and none are published to @types
, you'll need to create a local declaration file and either write the declarations yourself, or declare the module with out any other declarations and it will suppress the can't find module
errors.
Answered By - Kelly Copley
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.