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;
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)
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