neaumusic
neaumusic

Reputation: 10454

Efficient way to pass all valid props to child?

See example at bottom!

It lets me exclude:

  1. type='checkbox'
  2. className={CSS.checkbox + ' ' + CSS.mySpecialCheckbox}

and it allows the flexibility to:

  1. pool common styles in checkbox.sass
  2. pull unique styles from the parent class' associated .sass file, if it doesn't exist in the common pool (CSS['randomClass'] will fail, but the string was transpiled by parent's CSS reference, and will apply those styles)

The question is this -- sometimes we don't want to automagically forward all props into the <input> element, since React throws a warning about putting random attributes on a DOM element

Is there any tricky way to exclude certain props from getting passed on?

I'm thinking a spread operator with all applicable React eventHandlers + input attributes, but a more reasonable solution would be to contain all 'Real React/DOM attributes' in one random attribute, which I would prefer not to do.

I know this is confusing, but help is much appreciated.

Thanks


import React from 'react'
import CSS from '../css/checkbox.sass'

export default class Checkbox extends React.Component {
  render () {
    const className = (
      (CSS.checkbox) + ' ' +
      (CSS[this.props.className] || '') + ' ' +
      (this.props.className || '')
    );

    return (
      <input {...this.props} type='checkbox' className={className} />
    );
  }
}

<Checkbox className='circle' onClick={this.doSomething}>

Upvotes: 1

Views: 98

Answers (1)

neaumusic
neaumusic

Reputation: 10454

Ok I'm an idiot, I just realized the answer

The solution is to copy this.props then simply delete the ones that you know aren't applicable, but that you want to consume during the render phase

Similar to how I'm overriding className= after it would already have been declared, but instead of asdfBlahBlah='' which isn't valid, I just have to do:

let props = Object.assign({}, this.props);
delete props.asdfBlahBlah

return (<input {...props} type='checkbox' className={className}>)

Upvotes: 1

Related Questions