In my reactjs forms i need to upload an image and want to preview that image which is uploaded and then send an API request into database.
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
class AccountInfo extends Component {
constructor(props) {
super(props)
this.state = {
currentStep: 1,
userAccountData: {
userid: '',
useravtar: '',
attachement_id: '',
}
}
}
handleChange = event => {
const {name, value} = event.target
this.setState({
[name]: value
})
}
handleSubmit = event => {
let that = this;
const { AccountAction } = that.props;
event.preventDefault();
let accountInputs = {
userid: 49,
useravtar: that.state.image,
attachement_id: 478,
}
that.setState({
userAccountData: accountInputs,
})
AccountAction(accountInputs)
}
AccountInfoView = () => {
return (
<section id="account_sec" className="second_form">
<div className="container">
<React.Fragment>
<Formik
initialValues={{
file: null,
email: '',
phone: ''
}}
validationSchema={accountInfoSchema}
render={(values) => {
return(
<Form onSubmit={this.handleSubmit}>
<Step1
currentStep={this.state.currentStep}
handleChange={this.handleChange}
file= {this.state.image}
/>
</Form>
);
}}
/>
</React.Fragment>
)
}
render() {
return (
<div>{this.authView()}</div>
)
}
}
function Step1(props) {
if (props.currentStep !== 1) {
return null
}
return(
<div className="upload">
<input type="file" name="image" onChange={props.handleChange} />
<label htmlFor="profile">
<div className="imgbox">
<img src="images/trans_116X116.png" alt="" />
<img src={props.imgsrc} />
</div>
</label>
<span className="guide_leb">Add your avatar</span>
</div>
)
}
I have a multiple forms so i am using it in a Step wise.
Diego Bernal
Front-End Engineer
I haven't done work with this yet but a quick search yields this promising thread: github.com/jaredpalmer/formik/issues/926