Transfer { ..this.props } but exclude certain ones

Is it possible to transfer props down to child component where { ..this.props } is used for cleaner easier syntax, however exclude certain props like className or id?

You can employ destructuring to do this job:

const { className, id, ...newProps } = this.props; // eslint-disable-line
// `newProps` variable does not contain `className` and `id` properties

Since this syntax is currently ECMAScript proposal (Rest/Spread Properties) you will need to transpile code to enable this feature (e.g. using babel).

If you don’t mind using a third-party library, you can also use lodash’s omit function:

 { ..._.omit(this.props, ['className', 'id']) }

Key benefit: unlike madox2’s suggestion, you don’t pollute your scope with arbitrary variable names just to avoid passing certain props to child components. And also, at the time of writing this answer, you’re not dealing with experimental features either.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Is there support for static typing in ECMAScript 6 or 7?

Similar Posts