Reputation: 3989
My intent is to trigger the handleClick
method when the respective element is clicked so that the state's active
property is toggled between false
and true
. If being called inside render is what's causing the problem, how can I call the handleClick
method when that element is clicked?
import React, { Component } from 'react';
import styled from 'styled-components';
const NestedProperty = styled.div`
margin-left: 2rem;
`;
const ParentContainer = styled.div`
display: flex;
flex-direction: column;
`;
const NestedContainer = styled.div`
display: flex;
flex-direction: column;
`;
class SideMenuContainer extends Component {
constructor(props) {
super(props);
this.state = {
active: false
};
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
console.log("toggle click!")
this.setState({active : !this.state.active});
}
render() {
if (this.state.active == true){
return (
<ParentContainer>
<p onClick={() => this.props.handleClick()}>{this.props.parentName}</p>
<NestedContainer>
{this.props.properties.map(propertyElement => {
return (
<NestedProperty onClick={() => { this.props.changeInfoList(propertyElement.name, propertyElement.data_type, propertyElement.app_keys.join(', '))}} >
{propertyElement.name}
</NestedProperty>
);
})}
</NestedContainer>
</ParentContainer>
);
}
else {
return (
<ParentContainer>
<p onClick={this.handleClick()}>{this.props.parentName}</p>
</ParentContainer>
);
}
}
}
export default SideMenuContainer;
Upvotes: 0
Views: 27
Reputation: 3411
This will fix it.
else {
return (
<ParentContainer>
<p onClick={() => this.handleClick()}>{this.props.parentName}</p>
</ParentContainer>
);
}
You originally had this.
else {
return (
<ParentContainer>
<p onClick={this.handleClick()}>{this.props.parentName}</p>
</ParentContainer>
);
}
If you were going to do that you would need to exclude the () and do just this.handleClick
.
Upvotes: 2