D
D
dmitry-toster2020-05-06 23:44:49
JavaScript
dmitry-toster, 2020-05-06 23:44:49

How to pass only valid props to a React component?

For example, there is a component:

const { title, description } = this.state
<NewsComponent
  title,
  description
/>

How to transfer to it description, only if it exists, i.e. not undefined?
Is it possible at all or is it necessary to pass all the props, and inside NewsComponentit already do a check on what exists and what does not?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Suntsev, 2020-05-07
@dmitry-toster

There are many ways
to do this in a simple way, through the spread operator

const { ...rest } = this.state
<NewsComponent
  { ...rest }
/>

This way we will pass all existing parameters. Another thing is that most often in an internal component, something can refer to a non-existent parameter. Then you can just set it as default.
const { title, description = "" } = this.state
<NewsComponent
  title,
  description
/>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question