0

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
    )
  }
}
1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.