Home > OS >  How to use the t() function in a class component with a constructor?
How to use the t() function in a class component with a constructor?

Time:10-21

Using enter image description here

If I use interface ExampleProps extends WithTranslationProps {} the type incompatibility disappears, but I can't access the t function, because the WithTranslationProps only has a i18n? nullable type and I can't add anything to the ExampleProps, because I get Property 'newProperty' is missing in type 'WithTranslationProps' but required in type 'ExampleProps'.

const t1 = this.props.i18n?.t; results in TS2722: Cannot invoke an object which is possibly 'undefined' when trying to call t('Test').

const t2 = this.props.t; does not exists.

One solution, If I just initialize the state directly in the class, like:

class Example extends React.Component<ExampleProps, ExampleState> {
    state = {
      // set state here
    }

    render() {

Although I would still like to know if there is a way to use a constructor here.

CodePudding user response:

In react constructor and super methods receive either 0 parameters or 1 (if it's 1, then they should be props), as per documentation

In your render you can just do

render () {
   const { t } = this.props;

   return (
            <div>
                <p>{t('Test')}</p>
            </div>
        );
}

This deconstruction of the components props makes your code more readable, if you need more variables from props, just add a comma and the name of the variable, and it will be usable inside that function.

Other than that your code seems fine

CodePudding user response:

From the React documentation:

If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

But, wait a minute, what is the context you passed to constructor?

you only need to pass props as the parameter of the constructor.

constructor(props)

  • Related