Reputation: 23
I have a problem on my application: when a user is typing in the (and onChange is fired I suppose), even one single letter, the onClick event below is fired. Where is my mistake? I have simplified the code over and there (where you see the comments), there no relevant code in there! Thanks to everyone!
class Project extends React.Component {
constructor() {
super();
this.state = {
section_title: '',
sections: []
}
this.handleChange = this.handleChange.bind(this);
this.createSection = this.createSection.bind(this);
this.getSections = this.getSections.bind(this);
}
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
createSection(project_id) {
if(this.state.section_title != '') {
//Do Something here
}
}
getSections(project_id) {
//Fetch data here
}
componentDidMount() {
let project_data = this.props.project[0];
this.getSections(project_data.uid);
}
render() {
let project_data = this.props.project[0];
return (
<div>
<h2 className="ui header">
<i className="folder outline icon"></i>
<div className="content">
{project_data.title}
<div className="sub header">{he.decode(project_data.description)}</div>
</div>
</h2>
<div className="ui divider"></div>
<Modal trigger={<Button color="teal">Add New Section</Button>} closeIcon>
<Modal.Header>Add new section</Modal.Header>
<Modal.Content image>
<Modal.Description>
<Form>
<Form.Field>
<label>Section Name</label>
<input name="section_title" placeholder='Es: Slider ecc...' value={this.state.section_title} onChange={this.handleChange} />
</Form.Field>
<Button color="green" type='submit' onClick={this.createSection(project_data.uid)}>Crea Sezione</Button>
</Form>
</Modal.Description>
</Modal.Content>
</Modal>
</div>
);
}
}
Upvotes: 0
Views: 6660
Reputation: 1721
What you did is basically using the return data of your createSection
function for your onClick
So, on your onClick
, try
onClick={() => this.createSection(project_data.uid)}
The onChange
part is already correct.
This problem is similar to an existing answered question: React onClick function fires on render
Upvotes: 0
Reputation: 1064
in your Button you are initializing function this.createSection(project_data.uid)
instead of calling it when needed. Easiest way is to call via arrow function
onClick={() => this.createSection(project_data.uid)}
Upvotes: 3