Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correctly destructuring this.props for the whole component

I came across an issue today, consider following component:

export default class Input extends React.Component {
  someFunction() {
    console.log(this.props.value)
  }

  render () {
    const { type, value, required } = this.props
    return (
      <div className={cx('Input')}>
        <input type={type} value={value} required={required} />
      </div>
    )
  }
}

I am successfully destrucutring this.props and can use them within the render, however what if I need to use prop values outside of it i.e. inside someFunction() I am not sure to what would the consequences be if I move out constant { ... } and include right after export default class Input extends React.Component { line. Will this still be valid?

like image 665
Ilja Avatar asked Jun 29 '16 15:06

Ilja


People also ask

What is Destructuring in Reactjs?

Destructuring is a convenient way of creating new variables by extracting some values from data stored in objects or arrays. To name a few use cases, destructuring can be used to destructure function parameters or this. props in React projects for instance.


3 Answers

If you move it outside they would be null , because at that time constructor would not have got called.

It is a recommender approach to keep it in render or function because your parent component can change state which will cause your child to get rerendered ,So you need fresh props for every render .

like image 173
Piyush.kapoor Avatar answered Oct 17 '22 19:10

Piyush.kapoor


Correctly destructuring this.props for the whole component

Well you can't do that. Destructuring can only assign local variables so you'd need to destructure props in each function. Otherwise there's nothing wrong with having to write this.props.value. Use destructuring when it helps readability, not just because you don't feel like typing this.props.

I would write your code like this

// import cx from whatever

const someFunction = value=> console.log(value)

export const Input = ({type, value, required}) => (
  someFunction(value),
  <div className={cx('Input')}>
    <input type={type} value={value} required={required} />
  </div>
)
like image 32
Mulan Avatar answered Oct 17 '22 21:10

Mulan


Maybe consider updating it to a functional component.

function someFunction(props) {
  console.log(props.value)
}

function Input(props) {
  const { type, value, required } = props;

  someFunction(props); // logs props.value

  return (
    <div className={cx('Input')}>
      <input type={type} value={value} required={required} />
    </div>
  )
}

export default Input;
like image 3
RickTakes Avatar answered Oct 17 '22 19:10

RickTakes