Reputation: 46479
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?
Upvotes: 15
Views: 10434
Reputation: 135227
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>
)
Upvotes: 7
Reputation: 6803
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 .
Upvotes: 11
Reputation: 1197
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;
Upvotes: 3