Reputation: 23553
With pure functions in React it's easy to make any variable you create reusable by any other nested functions:
const myComponent = props => {
const {something} = props.nested;
const nestedFunction = () => {
if (something === "value") return true
}
const otherNestedFunction = () => {
console.log(otherNestedFunction)
}
return (
// markup
)
}
Can you do something similar with a React class? At the moment Im having to repeat creating the variable.
class myComponent extends React.Component() {
nestedFunction() {
const {something} = props.nested;
if (something === "value") return true
}
otherNestedFunction() {
const {something} = props.nested;
console.log(otherNestedFunction)
}
render(){
return (
// markup
)
}
}
Upvotes: 0
Views: 2892
Reputation: 83527
To share variables among functions of an ES6 class, use member variables. React provides props as a member variable which you can access with this.props
:
class myComponent extends React.Component() {
nestedFunction() {
if (this.props.nested === "value") return true
}
otherNestedFunction() {
console.log(this.props.nested)
}
render(){
return (
// markup
)
}
}
Note that you should never assign or otherwise chance the value of any props. Instead, use state with this.setState()
to update internal component state and trigger lifecycle events to update children components.
Upvotes: 2