j.doe
j.doe

Reputation: 4869

Access state outside the class

I am updating the width and height values each time the device rotates. I need this values to make some calculations. This is my code

function wp (percentage) {
    const value = (percentage * this.state.viewportWidth) / 100;
    return Math.round(value);
}
const height = this.state.viewportHeight * 0.45; // I am getting the error here

export default class MyClass extends Component {

      onLayout(e) {
        this.updateLayout()
      }

      componentDidMount() {
        this.updateLayout()
      }

      updateLayout = () => {
        const {width, height} = Dimensions.get('window')
        this.setState({viewportWidth: width });
        this.setState({viewportHeight: height });
      }
}

I am getting an error telling me the this.state.viewportHeight is undefined. Do you have any idea on how to solve that?

Upvotes: 1

Views: 5183

Answers (3)

Hitakshi Mahajan
Hitakshi Mahajan

Reputation: 61

Yes, you can access the state outside. You need to make an instance of the class using the new keyword

    new MyClass().state.viewportWidth

Upvotes: 2

linasmnew
linasmnew

Reputation: 3977

If your component stays in sync with the dimensions, then outside of your component you could just reference these dimensions directly through:

Dimensions.get('window').width and Dimensions.get('window').height

Upvotes: 1

Josh Pittman
Josh Pittman

Reputation: 7324

if you want to use the viewportWidth outside of the component then pass it into your function as a parameter.

function wp (percentage, width) {
    const value = (percentage * width) / 100;
    return Math.round(value);
}

It is unclear where you are calling the wp function from your code, but if you are calling it from inside the component then you need to replace it with wp(yourPercentageValue, this.state.viewportWidth)

You height calculation is just floating there so you can do the same and replace it with a function that takes the viewport

function hp (height) { return height * 0.45 }

Then you can call hp(this.state.viewportHeight) in your component.

State, in react, is the state of a component so you can never use it outside of a component. You can pass it into things though, either as a prop or parameter, which is what I did above.

Upvotes: 1

Related Questions