Shortcut for This.state in Reactjs

I am creating a Product create form and to make sure all inputs are filled in
I have created a if statement:

 if (this.state.Title != "" &&
            this.state.price != null &&
            this.state.Description != "" &&
            this.state.quantity != null)
            this.setState({ AllowCreate: true})

There are allot of “this.state”
I was wondering if there is a smarter/shorter way to code this?

if you are looking for syntactic sugar with a stateful class component, I believe there’s not much else you can do aside from assigning a variable name to this.state before the if statement.

If you are comfortable with React hooks, then you can assign each variable (e.g. title, price…) to useState() individually, and call it by a single-word variable name.

Got it. I know how hooks work. but i wanted to train myself in Class as well,
since some companys still use it.

Thanks for you comment

Hello there,

The most common pattern is to use destructuring:

const { Title, price, Description, quantity } = this.state;

// of logic

Hope this helps


destructuring is your friend with dealing with large variable names/pulling data from deep objects. You can even apply it directly in the function arguments/parameters. I recommend you master it, if you havent yet

1 Like

Great thank you so much

As the other have said, you can destructure the props into variables.
Then you are checking the values are not falseys. It would be shorter to check if they are truthys, i.e have a value.
If (title && price && description && quantity) this.setState…

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.