I'm trying to create an img uploader inside my ReduxForm that will only accept imgs that are .png and no larger than 210x210 and 2mb. Also, the design says to swap the placeholder img with the uploaded file which I'm also struggling with. Here's my code:
renderProfileImgUpload(field) {
const { meta: { touched, error }, label, name, accept, type } = field;
return (
<div>
<div className="login__fieldError">
<small>{touched ? error : ''}</small>
</div>
<label htmlFor="img-upload">
<img src="imgs/profile-select.png" className="img-responsive" alt="" />
</label>
<input type={type} name={name} accept={accept} id="img-upload" />
</div>
)
}
render() {
const { handleSubmit, showNextRegistration, showPreviousRegistration } = this.props;
return (
<div className="widgetFull--white">
<div className="align-middle row registration--fullHeight">
<div className="columns small-3">
<img
src="imgs/account-arrow-left.png"
alt="menu"
className="img-responsive"
onClick={showPreviousRegistration}
/>
</div>
<div className="columns small-6">
<h2 className="registration__header">Edit account</h2>
</div>
<div className="columns small-3">
<h3 className="registration__index">2 of 2</h3>
</div>
<form onSubmit={ handleSubmit(this.onSubmit.bind(this)) }>
<div className="columns small-3">
<Field label="Profile Image" type="file" name="image" accept="image/.png" component={this.renderProfileImgUpload} />
</div>
<div className="columns small-6">
<Field label="Username" type="screenname" name="screenname" component={this.renderUsernameField} />
</div>
<div className="columns small-6">
<Field label="First Name" type="firstName" name="firstName" component={this.renderFirstNameField} />
</div>
<div className="columns small-6">
<Field label="Last Name" type="lastName" name="lastName" component={this.renderLastNameField} />
</div>
<div className="columns small-12">
<button className="button expanded registration__btn" type="button">Next</button>
</div>
</form>
</div>
</div>
)
}
Currently I'm unsure whether it would be better to try and do the validation when uploading the img, or inside the handle submit function. Thanks for your help!
Related
I have form inside my react app,
And i would like to use this condition to validate the form before send the data to backend.
<div className="card-body">
<h3 className="mt-2 btn-primary text-center"> Diseño ChatBot </h3>
<Form
onSubmit={onSubmit}
validate={values => {
const errors = {};
if (!values.text || !values.link ||!values.image) {
errors.error = 'Es necesario cumplimentar uno de estos tres campo: Texto, Imagen, Link';
} else {errors.error = undefined;}
return errors;
}}
initialValues={{ title: title, text: text, link: link, link_title: link_title, image: image, image_title: image_title }}
render={({ handleSubmit, values, errors }) => (
<form id='editForm' className="row mt-4" onSubmit={handleSubmit} >
<div className="col-md-1 mb-4">
<label htmlFor="inputDescription" className="form-label text-center">
<h5> Título </h5>
</label>
</div>
<div className="col-md-11">
<Field
type="text"
className="form-control"
name='title'
component="input"
/>
</div>
<div className="col-md-1 mb-4">
<label htmlFor="inputResponse" className="form-label text-center" >
<h5> Texto </h5>
</label>
</div>
<div className="col-md-11">
<Field
className="form-control"
type="textarea"
name='text'
component="input"
/>
</div>
<div className="col-md-1 mb-4">
<label htmlFor="link" className="form-label text-center" >
<h5> Link </h5>
</label>
</div>
<div className="col-md-5">
<Field
className="form-control"
type="link"
name="link"
component="input"
/>
</div>
<div className="col-md-1">
<label htmlFor="link_title" className="form-label text-center" >
<h5> Title Link </h5>
</label>
</div>
<div className="col-md-5">
<Field
className="form-control"
type="text"
name='link_title'
component="input"
/>
</div>
<div className="col-md-1 mb-4">
<label htmlFor="image" className="form-label text-center" >
<h5> Image </h5>
</label>
</div>
<div className="col-md-5">
<Field
name="image"
type="file"
component={UploadImage}
/>
</div>
<div className="col-md-1">
<label htmlFor="image_title" className="form-label text-center" >
<h5> Title Image </h5>
</label>
</div>
<div className="col-md-5">
<Field
className="form-control"
type="text"
name='image_title'
component="input"
/>
</div>
<div>
{(isCreated && !isVariationsError) &&
<div className="alert alert-success" role='alert'>
Respuesta EDITADA Correctamente
</div>
}
</div>
<div className="buttons text-center">
<Volver className={"btn btn-outline-danger me-5 mb-3"} prevStep={prevStep} step={2}/>
<button className="btn btn-outline-warning me-5 mb-3" onClick={(e) => (e.preventDefault(), openPreview(values))} >Preview</button>
<SaveAndEdit className={"btn btn-outline-success me-5 mb-3"} idForm={'editForm'} text={'Guardar Cambios'}/>
<Cancelar className={"btn btn-outline-dark me-5 mb-3"} />
</div>
{errors.error && <Error meta={errors.error} /> }
<pre>{JSON.stringify(values, undefined, 2)}</pre>
<pre>{JSON.stringify(errors, undefined, 2)}</pre>
</form>
)}
/>
</div>
I have outside the form this Component Error with this:
const Error = (meta) => (
<h3 className="alert alert-danger text-center mt-5">{meta.meta}</h3>
);
If i use just with one condition like
validate={values => {
const errors = {};
if (!values.text) {
errors.error = 'Es necesario cumplimentar uno de estos tres campo: Texto, Imagen, Link';
} else {errors.error = undefined;}
return errors;
}}
works Fine, but if i try to use more conditions inside the conditional, not works.
Any idea to guide me?
Thanks
I have a Component that causes an error, "TypeError: Cannot read property 'value' of null". It's nested inside of another component, and makes that component not load.
This is the code:
const NewItem = (props) => {
const qty = "QuantityBox" + props.identifier.toString();
const prc = "PriceBox" + props.identifier.toString();
return(
<div className="NewItem">
<div className="ItemNameInput">
<p className="InputLabel">Item Name</p>
<input className="inputFull" type="text" />
</div>
<div className="QuantityAndPrice">
<div className="QuantityInput">
<p className="InputLabel">Qty</p>
<input className="inputEighth" value="1" id={qty} type="text" />
</div>
<div className="PriceInput">
<p className="InputLabel">Price</p>
<input className="inputFourth" value="0" id={prc} type="text" />
</div>
<div className="TotalOutput">
<p className="InputLabel">Total</p>
<h4 className="TotalAmount">{(document.getElementById(qty).value * document.getElementById(prc).value).toFixed(2)}</h4>
</div>
<img src={TrashCan} alt="Delete" />
</div>
</div>
)
}
Right in the "TotalAmount" h4, is where the problem arises. If I remove that part, it loads up just fine. Judging from the error, it can't find the elements I'm specifying, but I don't understand why. I don't know if it has anything to do with the parent component, but I'll put it here just in case:
class NewInvoice extends Component {
constructor(props) {
super(props)
this.state = {
numberOfItems: [0]
};
}
createItem = () => {
this.setState(prevState => ({numberOfItems: [...prevState.numberOfItems, (this.state.numberOfItems.length - 1)]}));
}
render() {
return(
<div className="NewInvoice">
<button onClick={() => this.props.goBackInvoiceList()} className="goBack">Go back</button>
<h1>New Invoice</h1>
<form>
<p className="FormAreaLabel">Bill From</p>
<div className="BillFrom">
<div className="StreetAddressInput">
<p className="InputLabel">Street Address</p>
<input className="inputFull" type="text" />
</div>
<div className="HalfInput">
<div className="CityInput">
<p className="InputLabel">City</p>
<input className="inputHalf" type="text" />
</div>
<div className="PostCodeInput">
<p className="InputLabel">Post Code</p>
<input className="inputHalf" type="text" />
</div>
</div>
<div className="NewCountryInput">
<p className="InputLabel">Country</p>
<input className="inputFull" type="text" />
</div>
</div>
<div className="BillTo">
<div className="ClientNameInput">
<p className="InputLabel">Client's Name</p>
<input className="inputFull" type="text" />
</div>
<div className="ClientEmailInput">
<p className="InputLabel">Client's Email</p>
<input className="inputFull" type="text" />
</div>
<div className="ClientStreetAddressInput">
<p className="InputLabel">Street Address</p>
<input className="inputFull" type="text" />
</div>
<div className="HalfInput">
<div className="ClientCityInput">
<p className="InputLabel">City</p>
<input className="inputHalf" type="text" />
</div>
<div className="ClientPostCodeInput">
<p className="InputLabel">Post Code</p>
<input className="inputHalf" type="text" />
</div>
</div>
<div className="ClientCountryInput">
<p className="InputLabel">Country</p>
<input className="inputFull" type="text" />
</div>
</div>
<div className="OtherInfo">
<div className="InvoiceDateInput">
<p className="InputLabel">Invoice Date</p>
<input className="inputFull" type="text" />
</div>
<div className="PaymentTermsInput">
<p className="InputLabel">Payment Terms</p>
<input className="inputFull" type="text" />
</div>
<div className="ProjectDescriptionInput">
<p className="InputLabel">Project Description</p>
<input className="inputFull" type="text" />
</div>
</div>
<h3 className="ItemListTitle">Item List</h3>
<div className="ItemList">
{this.state.numberOfItems.map((index) =>
<NewItem key={index} identifier={index} />
)}
<button onClick={() => this.createItem()} className="AddNewItem">+ Add New Item</button>
</div>
</form>
<div className="NewInvoiceEndButtons">
<button className="Discard">Discard</button>
<button className="SaveAsDraft">Save As Draft</button>
<button className="SaveAndSend">Save And Send</button>
</div>
</div>
)
}
}
This is happening because in the h4 line that you specified, you are trying to retrieve a DOM node with the id "QuantityBox" + props.identifier.toString(). Your code is unable to retrieve a DOM element with a matching id, causing document.getElementById(qty) to return null. null doesn't have any properties, so document.getElementById(qty).value is throwing an error specifiying that it cant access property value of null.
Also, if you want to manipulate DOM elements directly, the React way is to use React Refs. You should be able to achieve your desired result with that.
Read more on Refs here: https://reactjs.org/docs/refs-and-the-dom.html
i'm new in coding and i I still have a problem with if else condition, i have 2 authentication and one back end , one for react native and one for react ,
in Login i want to add is_store , i want to tell the system that if the username & password correct and is_sore = true , make him logged in and if the password right and the username right BUT is_store = false don't logged him in
i'm trying to pass is_store to Login component
i tried if condition but it give me wrong alert
Signup component
class RegistationForm extends Component {
state = {
username: "",
phone_number: "",
password: "",
email: "",
is_store: true <--- i want to pass it to Login
};
componentWillUnmount() {
this.props.errors.length && this.props.resetError();
}
changeHandler = e => {
this.setState({ [e.target.name]: e.target.value });
};
submitHandler = async e => {
e.preventDefault();
this.props.signup(this.state, this.props.history);
};
render() {
return (
<div className="container">
<div
style={{ marginTop: "125px" }}
className="card o-hidden border-0 shadow-lg col-12"
>
<div className="card-body p-0">
<div className="row">
<div className="col-lg-5 d-none d-lg-block bg-register-image col-12" />
<div className="col-lg-7 col-12">
<div className="p-5">
<div className="text-center col-12">
<h1 className="h4 text-gray-900 mb-4 col-12">
إنشاء حساب جديد
</h1>
</div>
<div className="text-center col-12">
{!!this.props.errors.length && (
<div className="text-left alert alert-danger">
{this.props.errors.map(error => (
<li key={error}>{error}</li>
))}
</div>
)}
</div>
<form onSubmit={this.submitHandler}>
<div className="form-group row">
<div className="col-sm-6 mb-3 mb-sm-0">
<Input
name="username"
value={this.state.username}
onChange={this.changeHandler}
className="form-control form-control-user"
placeholder=" السجل التجاري"
required
/>
</div>
<div className="col-sm-6 mb-3 mb-sm-0">
<Input
name="phone_number"
value={this.state.phone_number}
type="tel"
onChange={this.changeHandler}
className="form-control form-control-user"
placeholder="Mobile Ex: 966555555555"
required
pattern="[0-9]{12}"
/>
</div>
<br />
<br />
<div className="col-sm-6 mb-3 mb-sm-0">
<Input
name="password"
value={this.state.password}
onChange={this.changeHandler}
type="password"
className="form-control form-control-user"
placeholder="الرقم السري"
required
/>
</div>
<div className="col-sm-6 mb-3 mb-sm-0 ">
<Input
name="email"
value={this.state.email}
onChange={this.changeHandler}
type="email"
className="form-control form-control-user"
placeholder="الإيميل"
required
/>
</div>
<div className="col-12">
<button
style={{ padding: 9, marginTop: 20 }}
type="submit"
className="btn btn-success col-12 "
>
إنشئ حساب
</button>
</div>
</div>
</form>
<div className="text-center">
<Link to="/login" className="small">
املك حساب من قبل: تسجيل الدخول
</Link>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
Login component
class Login extends Component {
state = {
username: "",
password: "",
is_store: false <-- is here the right place?
};
componentWillUnmount() {
this.props.errors.length && this.props.resetError();
}
changeHandler = e => {
this.setState({ [e.target.name]: e.target.value });
};
submitHandler = async e => {
e.preventDefault();
## here is what i'm trying to do with is_store
if (this.state.is_store === true) {
this.props.login(this.state, this.props.history);
} else {
alert("Wrong");
}
};
render() {
return (
<div className="container">
<div className="row justify-content-center" style={{ marginTop: 125 }}>
<div className="col-xl-10 col-lg-12 col-md-9">
<div className="card o-hidden border-0 shadow-lg my-5">
<div className="card-body p-0">
<div className="row">
<div className="col-lg-6 d-none d-lg-block bg-login-image" />
<div className="col-lg-6">
<div className="p-5">
<div className="text-left">
<h1 className="h4 text-gray-900 mb-4">تسجيل الدخول</h1>
{!!this.props.errors.length && (
<div className="alert alert-danger" role="alert">
{this.props.errors.map(error => (
<li key={error}>{error}</li>
))}
</div>
)}
</div>
<form onSubmit={this.submitHandler}>
<div
className="form-group col-12"
style={{ padding: 0 }}
>
<Input
name="username"
className="form-control form-control-user"
onChange={this.changeHandler}
value={this.state.username}
placeholder="رقم السجل التجاري"
/>
</div>
<div
className="form-group col-12"
style={{ padding: 0 }}
>
<Input
type="password"
className="form-control form-control-user"
name="password"
value={this.state.passsword}
onChange={this.changeHandler}
placeholder="الرقم السري"
/>
</div>
<button
style={{ padding: 9 }}
type="submit"
className="btn btn-primary col-12"
>
دخول
</button>
<hr />
</form>
<hr />
<div className="text-center">
<NavLink to={`/signup`}>إنشاء حساب جديد</NavLink>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
this is authentication actions
export const login = (userData, history) => {
return async dispatch => {
try {
let response = await instance.post("user/login/", userData);
let user = response.data;
setAuthToken(user.token);
let decodedUser = jwt_decode(user.token);
dispatch(setCurrentUser(decodedUser));
history.push("/home");
} catch (error) {
console.log("error", error);
dispatch(setErrors(error.response.data));
}
};
};
thank you
In general, You can pass a state to a child component only. You can not pass a state from a child to its parent component.
In order to pass state to a parent component, you need to store that value. You can do it with Redux. Which stores the values and you can get that value in any component.
I have a form with steps.
I want other elements to appear after user passes one step.
There should be only one step visible at a time.
I tried for to use a boolean state variable without any luck. All steps appear after passing one.
return (
<UserConsumer>
{value => {
//const {dispatch} = value;
return (
<div>
<Animation pose={visible ? 'visible' : 'hidden'}>
<div className="card col-md-12 mb-4">
<div className="card-body">
<form onSubmit={this.changeVisibility}>
<div className="form-group">
<Text text="Adınız ve Soyadınız" />
</div>
<div className="form-group">
<Input ph="Ad ve Soyad" />
</div>
<Button clickText="İleri" />
</form>
</div>
</div>
</Animation>
<Animation pose={!visible ? 'visible' : 'hidden'}>
{queue.push(
<div className="card col-md-12 mb-4">
<div className="card-body">
<form onSubmit={this.changeVisibility}>
<div className="form-group">
<Text text="E-mail adresiniz" />
</div>
<div className="form-group">
<Input ph="E-mail" />
</div>
<Button clickText="İleri" />
</form>
</div>
</div>,
)}
</Animation>
</div>
)
}}
</UserConsumer>
)
I'm answering this based on your comment that it hides the first one but doesn't display the second one is because you are calling the push which will return the length of new array. So instead of elements from second Animation component it will display a number, fix:
return (
<UserConsumer>
{value => {
//const {dispatch} = value;
return (
<div>
<Animation pose={visible ? 'visible' : 'hidden'}>
<div className="card col-md-12 mb-4">
<div className="card-body">
<form onSubmit={this.changeVisibility}>
<div className="form-group">
<Text text="Adınız ve Soyadınız" />
</div>
<div className="form-group">
<Input ph="Ad ve Soyad" />
</div>
<Button clickText="İleri" />
</form>
</div>
</div>
</Animation>
<Animation pose={!visible ? 'visible' : 'hidden'}>
<div className="card col-md-12 mb-4">
<div className="card-body">
<form onSubmit={this.changeVisibility}>
<div className="form-group">
<Text text="E-mail adresiniz" />
</div>
<div className="form-group">
<Input ph="E-mail" />
</div>
<Button clickText="İleri" />
</form>
</div>
</div>
</Animation>
</div>
)
}}
</UserConsumer>
)
So I am trying to display the contents of three arrays in React in this fashion:
array[one,two]
array2[1,2]
array3[hi, bye]
what I want:
one
1
hi
two
2
bye
But I am ending up with
one
two
1
2
hi
bye
Here is the code and I am usnig paint info to map through and display. I tried nesting the ul's and the li's but not seeming to work... any advice would be greatly appreciated.
this.state = {
paintBrand: ['Sherwin-Williams'],
paintColor: ['Blue'],
paintSheen: ['Satin']
};
this.handleSubmit = this.handleSubmit.bind(this);
//Brads cool
}
handleSubmit(e) {
e.preventDefault();
var updateBrand = this.state.paintBrand;
updateBrand.push(this.refs.brand.value);
var updateColor = this.state.paintColor;
updateColor.push(this.refs.color.value);
var updateSheen = this.state.paintSheen;
updateSheen.push(this.refs.sheen.value);
this.setState({
paintBrand: updateBrand,
paintColor: updateColor,
paintSheen: updateSheen
});
}
render() {
var paintBrandArr = this.state.paintBrand;
paintBrandArr = paintBrandArr.map(brand =>
<li key={brand}>
{brand}
</li>
);
var paintColorArr = this.state.paintColor;
paintColorArr = paintColorArr.map(paint =>
<li key={paint}>
{paint}
</li>
);
var paintSheenArr = this.state.paintSheen;
paintSheenArr = paintSheenArr.map(sheen =>
<li key={sheen}>
{sheen}
</li>
);
return (
<div>
<form className="form" onSubmit={this.handleSubmit}>
<div className="row">
<div className="col-xs-4" />
<div className="col-xs-4">
<label htmlFor="brand">Paint Brand</label>
<div className="field">
<input
type="text"
name="brand"
className="form-control"
placeholder="Brand/Company"
ref="brand"
value={this.props.value}
onChange={this.props.onChange}
/>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-4" />
<div className="col-xs-4">
<label htmlFor="color">Color</label>
<div className="field">
<input
type="text"
name="brand"
className="form-control"
placeholder="Color"
ref="color"
value={this.props.value}
onChange={this.props.onChange}
/>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-4" />
<div className="col-xs-4">
<label htmlFor="brand">Sheen</label>
<div className="field">
<input
type="text"
name="brand"
className="form-control"
placeholder="Sheen"
ref="sheen"
value={this.props.value}
onChange={this.props.onChange}
/>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-12"> </div>
<input
className="btn btn-primary btn-lg"
type="submit"
value="Input"
/>
</div>
</form>
<div>
<div>
<ul>
{paintBrandArr}
{paintColorArr}
{paintSheenArr}
</ul>
</div>
</div>
</div>
);
}
}
What you could do is map over one array and get info from all the three arrays through index like
var paintBrandArr = this.state.paintBrand;
paintBrandArr = paintBrandArr.map((brand, index) =>
<li key={brand}>
{brand}
{paintColorArr[index]}
{paintSheenArr[index]}
</li>
);
and then in render
<ul>
{paintBrandArr}
</ul>