5

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:

enter image description here

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;
6
  • cant you do something like charsLeft && charsLeft >= 0 Commented Dec 10, 2019 at 14:51
  • Hmm yeah I tried that. Then I get the error on the next charsLeft after the && (charsLeft >= 0) Commented Dec 10, 2019 at 14:55
  • 1
    What's the reasoning behind the initial state of charsLeft being null? Would an initial state of 0 be more appropriate? Commented Dec 10, 2019 at 14:55
  • Whats the error you get when you add that line? Commented Dec 10, 2019 at 14:56
  • 2
    Is null required? can't you set it to this.props.maxChars initially? Commented Dec 10, 2019 at 14:56

2 Answers 2

9

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Change != to !== so you're checking the type and value. Unless you know what you're doing != should never be used.
Haha, it was too obvious for me to see it! Setting the initial state to my maxChars solved this issue. Thank you!
0

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
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.