abooayoob
abooayoob

Reputation: 91

props is undefined inside my function in es6 class component

I get Cannot read property 'callToPrayer' of undefined

import { adhaan } from './assets/audio.js'

export default class JustPrayClient extends Component {
  constructor (props) {
    super(props)
    // this.props = props   
    this.playSound.bind(this)
  }

  playSound () {
    // console.log(this.props.test)
    this.props.callToPrayer.play() //why is props undefined here?
  }

  render () {
    return (
      <View style={styles.container}>
        <Text onPress={this.playSound} style={styles.welcome}>
          Welcome to React Native! {this.props.test}
        </Text>
      </View>
    )
  }
}

const Main = () => <JustPrayClient callToPrayer={adhaan} test='hello' />

Does this have something to do with the this context?
If so, I don't know where/how I should bind this...

Upvotes: 0

Views: 3493

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 282130

You are not binding playSound function correctly in the constructor. You need to assign it back to the function like

this.playSound = this.playSound.bind(this)

Try this and it should fix you problem. However if you are using webpack and correctly specifying the presets in the module loaders then, binding with arrow functions also functions correclty

playSound = () = > {
   console.log(this.props.callToPrayer);
}

Also check if play() function is getting available to the playSound function once you console.log() it and if it is available then you can use it.

Upvotes: 2

yadhu
yadhu

Reputation: 15642

you have two choices:

.bind in constructor

  constructor (props) {
    super(props);
    this.playSound = this.playSound.bind(this);
  }

OR

use Arrow Function to define playSound

  playSound = () => {
    this.props.callToPrayer.play();
  }

Upvotes: 1

Related Questions