Last active
August 13, 2020 01:41
-
-
Save ypan887/92d6f1c5028388bd8a6851fdf034968d to your computer and use it in GitHub Desktop.
react - disable submit button (es6)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class UploadComponent extends React.Component { | |
constructor() { | |
super(); | |
this.state = { | |
title: '', // initial state for your input | |
desc: '', | |
image: '' | |
} | |
} | |
handleChange(e) { | |
name = e.target.name.match(/\[(.*?)\]/)[1]; // change state when input value changed | |
this.setState({ | |
[name]: e.target.value // dynamic key name with [] | |
}); | |
} | |
render() { | |
const validForm = this.state.title && this.state.desc && this.state.image; // changed when state has changed, empty string will return false in JS | |
return ( | |
<div> | |
<form action="/images" className="col s12" method="post" acceptCharset="UTF-8" encType='multipart/form-data'> | |
<div className="row"> | |
<input type='hidden' name='authenticity_token' value={ this.props.csrfToken } /> | |
<div className="input-field col s12"> | |
<input placeholder="Title" name="image[title]" type="text" className="validate" value={ this.state.title } onChange={ this.handleChange.bind(this) } /> // call back on change | |
<label htmlFor="first_name">Title</label> | |
</div> | |
<div className="input-field col s12"> | |
<input name="image[desc]" type="text" className="validate" value={ this.state.desc } onChange={ this.handleChange.bind(this) } /> | |
<label htmlFor="desc">Description</label> | |
</div> | |
<div className="file-field input-field col s12"> | |
<div className="btn"> | |
<span>Choose a image</span> | |
<input type="file" name="image[image]" accept="image/*" value={ this.state.image } onChange={ this.handleChange.bind(this) } /> | |
</div> | |
<div className="file-path-wrapper"> | |
<input className="file-path validate" type="text" /> | |
</div> | |
</div> | |
<div className="col s12"> | |
<button type='submit' className='submit btn waves-effect waves-light' name="action" disabled={ !validForm }>Upload</button> // button disabled based on the value of a const calculated by state | |
</div> | |
</div> | |
</form> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment