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?
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.
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 .
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>
)
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With