Reputation: 687
I'm trying to convert a react project into TypeScript. The code below is an input field that counts how many characters that is being inputed.
In the renderCharactersLeft function I get the following error:
This doesn't really surprise me since the default state 'charsLeft' is set to null, but I wonder how you would bypass or solve this message in TypeScript?
import React from "react";
interface CharCountInputProps {
value: string;
type: string;
name: string;
maxChars: number;
onChange: any;
}
interface CharCountInputState {}
class CharCountInput extends React.Component<
CharCountInputProps,
CharCountInputState
> {
state = {
charsLeft: null
};
componentDidMount() {
this.handleCharCount(this.props.value);
}
handleCharCount = (value: string) => {
console.log(value);
const { maxChars } = this.props;
const charCount = value.length;
const charsLeft = maxChars - charCount;
this.setState({ charsLeft });
};
changeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ [event.target.name]: event.target.value } as Pick<
CharCountInputState,
keyof CharCountInputState
>);
this.handleCharCount(event.target.value);
this.props.onChange(event);
};
renderCharactersLeft = () => {
const { charsLeft } = this.state;
let content;
if (charsLeft >= 0) {
content = <span>{`characters left: ${charsLeft}`}</span>;
} else if (charsLeft != null && charsLeft < 0) {
const string = charsLeft.toString().substring(1);
content = <span>{`too many characters: ${string}`}</span>;
} else {
content = null;
}
return content;
};
render() {
const { value, type, name } = this.props;
return (
<>
<input
onChange={this.changeHandler}
value={value}
type={type}
name={name}
/>
{this.renderCharactersLeft()}
</>
);
}
}
export default CharCountInput;
Upvotes: 5
Views: 7563
Reputation: 63
Another alternative is You can create local variable and assign the charLeft to it and use the local variable for compare.
let newVariable = charLeft;
if(newVariable > 0) {
//do coding
}
Upvotes: 0
Reputation: 405
You could add a null check to your if-statement like this:
if (charsLeft !== null && charsLeft >= 0) {
or alternatively set the initial state for charsLeft to something other than null (ex. maxChars from your props)
Upvotes: 9