Reputation: 191
I browsed the answer to many questions here on this subject, and I think I doing everything I should but somehow it does not work.
Here is the isolated part of code throwing the error:
import React from 'react';
import Switchbookmarks from './switch';
class App extends React.Component {
test(str){
console.log(str)
}
render(){
return (
<div className="App">
<Switchbookmarks>test={this.test.bind(this)}</Switchbookmarks>
</div>
);
}
}
export default App;
and switch.js file:
import React, { Component } from 'react'
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Switch from '@material-ui/core/Switch';
class Switchbookmarks extends Component{
constructor(props) {
super(props);
this.state ={
checkedA:false
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
this.setState({ [event.target.name]: event.target.checked });
if (event.target.checked) {
this.props.test(event.target.checked);
}
};
render (){
return(
<div style={{marginLeft: '65%', position: 'fixed'}}>
<FormControlLabel
control={<Switch checked={this.state.checkedA} onChange={this.handleChange} name="checkedA" />}
label="Zakładki"
/>
</div>
)};
}
export default Switchbookmarks
I want to control other sibling component visibility based on the switch value. When the handleCHange is invoked it throws an error
TypeError: this.props.test is not a function.
What am I doing wrong here or is there any other method to accomplish this?
Upvotes: 0
Views: 1112
Reputation: 367
I'm pretty confident you cannot bind the way you did. You should either bind in the construction and pass the props as "this.test" or simply change the test function to arrow function, and the test props EDIT: I don't even think you need to bind anything. simply pass the test as props.
test = (str) => {
console.log(str)
}
.....
<Switchbookmarks test={this.test}></Switchbookmarks>
Upvotes: 0
Reputation: 5972
<Switchbookmarks>test={this.test.bind(this)}</Switchbookmarks>
Do you see the closed >
? It could be an possible issue.
<Switchbookmarks test={this.test.bind(this)}</Switchbookmarks>
Upvotes: 1