I have this object:
const itemDataObject = {
sort: '',
title_item_lateral: '',
text_item_lateral: '',
image_lateral: [
{
title_image_lateral: '',
path_image_lateral: '',
},
],
document_lateral: '',
links: [
{
title_link: '',
link: '',
},
],
};
and i need to fill it in a form.
i use this function:
const handleChange = (i, e) => {
let itemData = [...item_lateral];
itemData[i][e.target.name]=e.target.value;
setItems(itemData);
setNewLateral({...lateral, item_lateral, title_lateral});
handleChangeChat(e); };
and this inside the form:
<div>
{item_lateral.map((input, i) => (
<>
{ !(input.button_pressed === 'image' || input.button_pressed ===
'links') &&
<div className="row align-item_lateral-center" key=
{input.button_pressed + i + 1}>
<div className="col-2 mt-3">
<h3>{input.button_pressed}</h3>
</div>
<div className="col-10">
<input
placeholder={input.button_pressed}
id={i}
className='form-control mt-3'
name={input.button_pressed}
onChange= {e => handleChange(i, e)}
type="text"
/>
</div>
</div>
}
{ input.button_pressed === 'image' &&
<>
<div className="row align-item_lateral-center row" key=
{input.button_pressed + i + 2}>
<div className="col-2">
<h3>Imagen: </h3>
</div>
<div className='col-10'>
<input
placeholder='title_image_lateral'
id={i}
className='form-control mt-3'
name='title_image_lateral'
onChange= {e => handleChange(i, e)}
type="text"
/>
</div>
</div>
<div className="row align-item_lateral-center row" key=
{input.button_pressed + i + 1}>
<div className="col-2">
<h3>Image Path: </h3>
</div>
<div className='col-10'>
<input
placeholder='path_image_lateral'
id={i}
className='form-control mt-3'
name='path_image_lateral'
onChange= {e => handleChange(i, e)}
type="text"
/>
</div>
</div>
</>
}
{input.button_pressed === 'links' &&
<>
<div className="row align-item_lateral-center row" key=
{input.button_pressed + i+2}>
<div className="col-2">
<h3>Title Link: </h3>
</div>
<div className="col-8">
<input
placeholder='titel_link'
id={i}
className='form-control mt-3'
name='titel_link'
onChange= {e => handleChange(i, e)}
type="text"
/>
</div>
</div>
<div className="row align-item_lateral-center row" key={i}>
<div className="col-2">
<h3>Link: </h3>
</div>
<div className="col-8">
<input
placeholder='link'
id={i}
className='form-control mt-3'
name='link'
onChange= {e => handleChange(i, e)}
type="text"
/>
</div>
</div>
</>
}
</>
))}
</div>
The form works onsubmit, and create values in the object with the property name, and the value.
But if the property (p.e: 'title_image_lateral'), not put the new value in the correct place in the object, instead create a new element in the root of the object: title_image_lateral: (value submited in the form).
I thik that i can change the 'root' for the itemData[i][e.target.name]=e.target.value; , but i can not achieve.
Maybe i can create state for this values, and then onsubmit the form, set in the object...but maybe is made a big surround.
Some light for my issue.
Thanks.
Here the entire file:
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
const LateralWindow = ({token}) => {
const itemDataObject = {
sort: '',
title_item_lateral: '',
text_item_lateral: '',
image_lateral: [
{
title_image_lateral: '',
path_image_lateral: '',
},
],
document_lateral: '',
links: [
{
title_link: '',
link: '',
},
],
};
const dispatch = useDispatch();
const generalInfo = useSelector(state=> state.faqsGralInfo);
const {
description,
typeResponse,
rolViews,
workLoadLevel,
id,
id_intent,
corpusArea,
corpusName,
} = generalInfo;
const [ finalResponse, setFinalResponse ] = useState({});
const [ newJsonResponse, setNewJsonResponse ] = useState( {});
const [ title_lateral, setTitleLateral ] = useState('');
const [ item_lateral, setItems ] = useState([]);
const [ lateral, setNewLateral] = useState({
title_lateral: title_lateral,
item_lateral: [item_lateral]
});
let buttonPressed;
const [nameValue, setNameValue] = useState(['inicial']);
console.log(nameValue);
const addFields = (e) => {
e.preventDefault();
buttonPressed = e.target.value;
setNameValue(buttonPressed);
let newItemField;
newItemField = { ...itemDataObject, button_pressed: buttonPressed };
setItems([...item_lateral, newItemField]);
};
const handleChangeChat = (e) => {
setFinalResponse({...finalResponse, [e.target.name]: e.target.value});
setNewJsonResponse({
...newJsonResponse,
accesToken: token,
newDataResponse: {
description,
typeResponse,
rolViews,
workLoadLevel,
id,
id_intent,
response_json_new:{finalResponse, lateral},
corpusArea,
corpusName,
lateral_W: generalInfo.lateral_W === 'true' ? 1 : 0 ,
}
},
);
};
const handleChange = (i, e) => {
let itemData = [...item_lateral];
itemData[i][e.target.name]=e.target.value;
setItems(itemData);
setNewLateral({...lateral, item_lateral, title_lateral});
handleChangeChat(e); };
const submitForm = (e) => {
e.preventDefault();
};
const sendToCorpus = () => {
/* setTimeout(() => {
window.location = '/corpus';
}, 3000); */
};
return (
<>
<div className="card mb-3">
<div className="card-body">
<h2> Diseño Chat </h2>
<form className="row mt-4" onSubmit={submitForm} >
<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">
<input
type="text"
className="form-control"
name='title'
onChange={handleChangeChat}
id="inputDescription"
required
/>
</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">
<input
type="textarea"
className="form-control"
name='text'
onChange={handleChangeChat}
id="inputResponse"
required
/>
</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">
<input
type="link"
className="form-control"
name="link"
onChange={handleChangeChat}
id="link"
required
/>
</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">
<input
type="text"
className="form-control"
name='link_title'
onChange={handleChangeChat}
id="link_title"
required
/>
</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">
<input
type="file"
className="form-control"
name="image"
onChange={handleChangeChat}
id="image"
required
/>
</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">
<input
type="text"
className="form-control"
name='image_title'
onChange={handleChangeChat}
id="image_title"
required
/>
</div>
<div className="mt-5" >
<h3>DISEÑO VENTANA LATERAL</h3>
</div>
<h5 className="ms-5 mb-5 mt-5"> Diseña tu respuesta añadidendo subtitulos, texto, imagenes, documentos y enlaces.
Puedes seleccionarlos con el orden que mejor se ajuste a tu respuesta. Y puedes poner tantos elementos como quieras. </h5>
<div className="container">
<div className="row align-item_lateral-center" >
<div className="col-2 mt-3">
<h3>Título Ventana Lateral</h3>
</div>
<div className="col-10">
<input
placeholder= 'Título Ventana Lateral'
className='form-control mt-3'
value={title_lateral}
onChange= {e=> setTitleLateral(e.target.value)}
type="text"
/>
</div>
</div>
<div>
{item_lateral.map((input, i) => (
<>
{ !(input.button_pressed === 'image' || input.button_pressed === 'links') &&
<div className="row align-item_lateral-center" key={input.button_pressed + i + 1}>
<div className="col-2 mt-3">
<h3>{input.button_pressed}</h3>
</div>
<div className="col-10">
<input
placeholder={input.button_pressed}
id={i}
className='form-control mt-3'
name={input.button_pressed}
onChange= {e => handleChange(i, e)}
type="text"
/>
</div>
</div>
}
{ input.button_pressed === 'image' &&
<>
<div className="row align-item_lateral-center row" key={input.button_pressed + i + 2}>
<div className="col-2">
<h3>Imagen: </h3>
</div>
<div className='col-10'>
<input
placeholder='title_image_lateral'
id={i}
className='form-control mt-3'
name='title_image_lateral'
onChange= {e => handleChange(i, e)}
type="text"
/>
</div>
</div>
<div className="row align-item_lateral-center row" key={input.button_pressed + i + 1}>
<div className="col-2">
<h3>Image Path: </h3>
</div>
<div className='col-10'>
<input
placeholder='path_image_lateral'
id={i}
className='form-control mt-3'
name='path_image_lateral'
onChange= {e => handleChange(i, e)}
type="text"
/>
</div>
</div>
</>
}
{input.button_pressed === 'links' &&
<>
<div className="row align-item_lateral-center row" key={input.button_pressed + i+2}>
<div className="col-2">
<h3>Title Link: </h3>
</div>
<div className="col-8">
<input
placeholder='titel_link'
id={i}
className='form-control mt-3'
name='titel_link'
onChange= {e => handleChange(i, e)}
type="text"
/>
</div>
</div>
<div className="row align-item_lateral-center row" key={i}>
<div className="col-2">
<h3>Link: </h3>
</div>
<div className="col-8">
<input
placeholder='link'
id={i}
className='form-control mt-3'
name='link'
onChange= {e => handleChange(i, e)}
type="text"
/>
</div>
</div>
</>
}
</>
))}
</div>
<div className="mt-5 text-center">
<button className="btn btn-primary me-4 mb-4" value="text_item_lateral" onClick={addFields}>
Add Text
</button>
<button className="btn btn-primary me-4 mb-4" value="title_item_lateral" onClick={addFields}>
Add Subtitle
</button>
<button className="btn btn-primary me-4 mb-4" value="image" onClick={addFields}>
Add Image
</button>
<button className="btn btn-primary me-4 mb-4" value="document_lateral" onClick={addFields}>
Add document
</button>
<button className="btn btn-primary me-4 mb-4" value="links" onClick={addFields}>
Add Links
</button>
</div>
</div>
<div>
</div>
<div>
{(isCreated && isVariationsSave) &&
<div className="alert alert-success" role='alert'>
Respuesta CREADA Correctamente
</div>
}
{isCreated && sendToCorpus()}
</div>
<button className="btn btn-warning me-5 mb-3" type="submit" >Preview</button>
<button className="btn btn-success me-5 mb-3" type="submit">Guardar Respuesta</button>
</form>
<div className="text-center">
</div>
</div>
</div>
</>
);
};
export default LateralWindow;
Check if this suits your needs:
import { useState } from "react";
import { useSelector } from "react-redux";
const LateralWindow = ({ token }) => {
const itemDataObject = {
sort: "",
title_item_lateral: "",
text_item_lateral: "",
image_lateral: {
title_image_lateral: "",
path_image_lateral: "",
},
document_lateral: "",
links: {
title_link: "",
link: "",
},
};
const generalInfo = useSelector((state) => state.faqsGralInfo);
const { description, typeResponse, rolViews, workLoadLevel, id, id_intent, corpusArea, corpusName } = generalInfo;
const [finalResponse, setFinalResponse] = useState({});
const [newJsonResponse, setNewJsonResponse] = useState({});
const [title_lateral, setTitleLateral] = useState("");
const [item_lateral, setItems] = useState([]);
const [lateral, setNewLateral] = useState({
title_lateral: title_lateral,
item_lateral: [item_lateral],
});
let buttonPressed;
const addFields = (e) => {
e.preventDefault();
buttonPressed = e.target.value;
let newItemField;
newItemField = { ...itemDataObject, button_pressed: buttonPressed };
setItems([...item_lateral, newItemField]);
};
const handleChangeChat = (e) => {
setFinalResponse({ ...finalResponse, [e.target.name]: e.target.value });
setNewJsonResponse({
...newJsonResponse,
accesToken: token,
newDataResponse: {
description,
typeResponse,
rolViews,
workLoadLevel,
id,
id_intent,
response_json_new: { finalResponse, lateral },
corpusArea,
corpusName,
lateral_W: generalInfo.lateral_W === "true" ? 1 : 0,
},
});
};
const handleChange = (i, e) => {
let itemData = [...item_lateral];
let elementChanged = e.target;
let name = elementChanged.name;
let value = elementChanged.value;
if (name === "title_image_lateral" || name === "path_image_lateral") {
itemData[i].image_lateral[name] = value;
} else if (name === "title_link" || name === "link") {
itemData[i].links[name] = value;
} else {
itemData[i][name] = value;
}
setItems(itemData);
setNewLateral({ ...lateral, item_lateral, title_lateral });
handleChangeChat(e);
};
const submitForm = (e) => {
console.log(item_lateral);
e.preventDefault();
};
return (
<>
<div className="card mb-3">
<div className="card-body">
<h2> Diseño Chat </h2>
<form className="row mt-4" onSubmit={submitForm}>
<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">
<input type="text" className="form-control" name="title" value="Titulo" onChange={handleChangeChat} id="inputDescription" required />
</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">
<input type="textarea" className="form-control" name="text" value="Texto" onChange={handleChangeChat} id="inputResponse" required />
</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">
<input type="link" className="form-control" name="link" value="link" onChange={handleChangeChat} id="link" required />
</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">
<input type="text" className="form-control" name="link_title" value="testeLink" onChange={handleChangeChat} id="link_title" required />
</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">
<input type="file" className="form-control" name="image" onChange={handleChangeChat} id="image" required />
</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">
<input
type="text"
className="form-control"
name="image_title"
value="title image"
onChange={handleChangeChat}
id="image_title"
required
/>
</div>
<div className="mt-5">
<h3>DISEÑO VENTANA LATERAL</h3>
</div>
<h5 className="ms-5 mb-5 mt-5">
Diseña tu respuesta añadidendo subtitulos, texto, imagenes, documentos y enlaces. Puedes seleccionarlos con el orden que mejor se ajuste
a tu respuesta. Y puedes poner tantos elementos como quieras.{" "}
</h5>
<div className="container">
<div className="row align-item_lateral-center">
<div className="col-2 mt-3">
<h3>Título Ventana Lateral</h3>
</div>
<div className="col-10">
<input
placeholder="Título Ventana Lateral"
className="form-control mt-3"
value={title_lateral}
onChange={(e) => setTitleLateral(e.target.value)}
type="text"
/>
</div>
</div>
<div className="mt-5 text-center">
<button className="btn btn-primary me-4 mb-4" value="text_item_lateral" onClick={addFields}>
Add Text
</button>
<button className="btn btn-primary me-4 mb-4" value="title_item_lateral" onClick={addFields}>
Add Subtitle
</button>
<button className="btn btn-primary me-4 mb-4" value="image" onClick={addFields}>
Add Image
</button>
<button className="btn btn-primary me-4 mb-4" value="document_lateral" onClick={addFields}>
Add document
</button>
<button className="btn btn-primary me-4 mb-4" value="links" onClick={addFields}>
Add Links
</button>
</div>
<div>
{item_lateral.map((input, i) => {
return (
<div key={input.button_pressed + i}>
{!(input.button_pressed === "image" || input.button_pressed === "links") && (
<div className="row align-item_lateral-center">
<div className="col-2 mt-3">
<h3>{input.button_pressed}</h3>
</div>
<div className="col-10">
<input
placeholder={input.button_pressed}
id={i}
className="form-control mt-3"
name={input.button_pressed}
onChange={(e) => handleChange(i, e)}
type="text"
/>
</div>
</div>
)}
{input.button_pressed === "image" && (
<>
<div className="row align-item_lateral-center row">
<div className="col-2">
<h3>Imagen: </h3>
</div>
<div className="col-10">
<input
placeholder="title_image_lateral"
id={i}
className="form-control mt-3"
name="title_image_lateral"
onChange={(e) => handleChange(i, e)}
type="text"
/>
</div>
</div>
<div className="row align-item_lateral-center row">
<div className="col-2">
<h3>Image Path: </h3>
</div>
<div className="col-10">
<input
placeholder="path_image_lateral"
id={i}
className="form-control mt-3"
name="path_image_lateral"
onChange={(e) => handleChange(i, e)}
type="text"
/>
</div>
</div>
</>
)}
{input.button_pressed === "links" && (
<>
<div className="row align-item_lateral-center row">
<div className="col-2">
<h3>Title Link: </h3>
</div>
<div className="col-8">
<input
placeholder="title_link"
id={i}
className="form-control mt-3"
name="title_link"
onChange={(e) => handleChange(i, e)}
type="text"
/>
</div>
</div>
<div className="row align-item_lateral-center row">
<div className="col-2">
<h3>Link: </h3>
</div>
<div className="col-8">
<input
placeholder="link"
id={i}
className="form-control mt-3"
name="link"
onChange={(e) => handleChange(i, e)}
type="text"
/>
</div>
</div>
</>
)}
</div>
);
})}
</div>
</div>
<div></div>
<div>
{isCreated && isVariationsSave && (
<div className="alert alert-success" role="alert">
Respuesta CREADA Correctamente
</div>
)}
{isCreated && sendToCorpus()}
</div>
<button className="btn btn-warning me-5 mb-3" type="submit">
Preview
</button>
<button className="btn btn-success me-5 mb-3" type="submit">
Guardar Respuesta
</button>
</form>
<div className="text-center"></div>
</div>
</div>
</>
);
};
export default LateralWindow;
Related
I am trying to create a register page where a user can add a profile picture as well as a background picture to their profile. I have installed the PrimeReact themes and templates to my node modules. However, the avatar doesn't want to fit it to where it can make a background image avatar. Instead, it just fits it as a circle just like the profile picture avatar instead of a rectangle fit as a background image avatar.
import {useState, useEffect } from 'react'
import Avatar from 'react-avatar-edit'
import {Dialog} from 'primereact/dialog'
import {InputText} from 'primereact/inputtext'
const initialState = {
company: '',
email: '',
password: '',
isMember: true,
}
const Register = () => {
const [imagecrop, setimagecrop] = useState(false);
const [image, setImage] = useState("");
const [src, setsrc] = useState(false);
const [profile, setProfile] = useState([]);
const [pview, setpview] = useState(false);
const profileFinal = profile.map((item) => item.pview);
const onClose = () => {
setpview(null);
};
const onCrop = (view) => {
setpview(view);
};
const saveCropImage = () => {
setProfile([...profile, { pview }]);
setimagecrop(false);
}
const [values, setValues] = useState(initialState)
// global state and useNavigate
const handleChange = (e) => {
console.log(e.target)
}
const onSubmit = (e) => {
e.preventDefault()
console.log(e.target)
}
return (
<body class="page-template-default page page-id-13">
<header class="site-header">
<div class="container">
<h1 class="school-logo-text float-left"><strong>Direct</strong> Connection</h1>
<div class="site-header__util">
</div>
</div>
</header>
<div class="page-banner">
<div class="page-banner__bg-image" style={ { backgroundImage: "url('connection.jpg')" } }></div>
<div class="page-banner__content container container--narrow">
<h1 class="page-banner__title">Add Your Company</h1>
<div class="page-banner__intro">
<p></p>
</div>
</div>
</div>
<div class="container container--narrow page-section">
<h2 class="headline headline--tiny">Want to join and connect with companies? Sign up and get your company out there:</h2>
<label class="profile-pic">Profile Photo:</label>
<div class="profile-img">
<Dialog
visible={imagecrop}
header={() => (
<p htmlFor="" class="text 2xl font-semibold textColor">
</p>
)}
onHide={() => setimagecrop(false)}
></Dialog>
<div class="confirmation-content flex flex-column align-items-center">
<Avatar
width={500}
height={400}
onCrop={onCrop}
onClose={onClose}
src={src}
shadingColor={"#474649"}
backgroundColor={"#474649"}
></Avatar>
<div class="flex flex-column align-items-center mt-5 w-12">
<div class="flex justify-content-around w-12 mt-4">
</div>
</div>
<InputText
type="file"
accept='/image/*'
style={{ display: "none" }}
onChange={(event)=>{
const file = event.target.files[0];
if(file && file.type.substring(0,5)==="image"){
setImage(file);
}else{
setImage(null)
}
}}
/>
</div>
</div>
<script src="profile-pic.js"></script>
<label class="profile-back">Background Photo:</label>
<div>
<Dialog
visible={imagecrop}
header={() => (
<p htmlFor="" class="text 2xl font-semibold textColor">
</p>
)}
onHide={() => setimagecrop(false)}
></Dialog>
<Avatar
width={1000}
height={400}
onCrop={onCrop}
onClose={onClose}
src={src}
shadingColor={"#474649"}
backgroundColor={"#474649"}
></Avatar>
<InputText
type="file"
accept='/image/*'
style={{ display: "none" }}
onChange={(event)=>{
const file = event.target.files[0];
if(file && file.type.substring(0,5)==="image"){
setImage(file);
}else{
setImage(null)
}
}}
/>
<img class="background-image" src=""></img>
</div>
<div class="company-info-container page-section">
<label class="company-name">Company Name</label>
<div class="company-input">
<input text="headline headline--input" placeholder="Enter Company"></input>
</div>
<label class="company-email">Email</label>
<div class="email-input">
<input text="headline headline--input" placeholder="Enter Email"></input>
</div>
<label class="company-address">Company Address</label>
<div class="address-input">
<input text="headline headline--input" placeholder="Enter Address"></input>
</div>
<label class="company-city">City</label>
<div class="city-input">
<input text="headline headline--input" placeholder="Enter City"></input>
</div>
<label class="company-zip">Zip Code</label>
<div class="zip-input">
<input text="headline headline--input" placeholder="Enter Zip"></input>
</div>
<label class="company-password">Password</label>
<div class="password-input">
<input text="headline headline--input" placeholder="Enter Password"></input>
</div>
<label class="company-password">Retype Password</label>
<div class="reword-input">
<input text="headline headline--input" placeholder="Re Password"></input>
</div>
<label class="company-description">Tell us about your company and what you do!</label>
<div class="description-input">
<textarea rows="5" cols="80" id="TITLE" text="headline headline--input" placeholder="Description"></textarea>
</div>
</div>
<button type="button" class="btn btn--large btn--orange push-right">Add Your Company</button>
</div>
<footer class="site-footer">
<div class="site-footer__inner container container--narrow">
<div class="group">
<div class="site-footer__col-one">
<h1 class="school-logo-text school-logo-text--alt-color">
<strong>Direct</strong> Connection
</h1>
<p><a class="site-footer__link" href="index.html">706-263-0175</a></p>
</div>
</div>
</div>
</footer>
</body>
)
}
export default Register
I have tried looking at how primereact avatars can reshape the circle to rectangle to fit the image to a background image but I don't see many ways of how it can be reshaped.
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'm trying to create this 3 button but I can't create third button because I don't know how use multiple useState in React Js.
This is my code :
const ShowOrNot = () => {
const [showForm, setShowForm] = useState(false);
const [showPreview , setShowPreview] = useState(false)
return (
<div className="col-12">
{showForm ? (
<div className={"content-send-form-wrapper"} id="scrollbar-style">
<div className={"content-send-form-header"}>
<div className={"content-send-form-header-title"}>
</div>
<h2>
New Upload
</h2>
<div className={"content-send-form-close-btn"}>
<button onClick={() => setShowForm(false)} className={"close-modal-btn"}>
Close <span></span>
</button>
</div>
</div>
<form className={"mt-3 content-send-form-data register-teacher-inputs-box "}>
<Row>
<div className={"col-lg-6 col-12 mt-4"}>
<label
htmlFor={"name"} className={" text-right"}>
<span>*</span>
</label>
<input type="text" className="form-control" placeholder={"عنوان"}
name={""} required="true"
// value={this.name}
// onChange={this.onChange}
onBlur={(e) => e.target.placeholder = "عنوان"}
onFocus={(e) => e.target.placeholder = ""}
/>
</div>
<div className={"col-lg-6 col-12 mt-4"}>
<label
htmlFor={"country"} className={" text-right"}>
<span>*</span>
</label>
<input type="text" className="form-control" placeholder={"دسته بندی"}
name={"country"}
// value={this.country}
// onChange={this.onChange}
required="true"
onBlur={(e) => e.target.placeholder = "دسته بندی"}
onFocus={(e) => e.target.placeholder = ""}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3">
<label
htmlFor={"name"} className={"label-full-size text-right"}>
<span>*</span>
</label>
<input type="text" className="form-control" placeholder={"خلاصه توضیحات"}
name={""} required="true"
// value={this.name}
// onChange={this.onChange}
onBlur={(e) => e.target.placeholder = "خلاصه توضیحات"}
onFocus={(e) => e.target.placeholder = ""}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3">
<label
htmlFor={"name"} className={"label-full-size text-right textarea-label"}>
<span>*</span>
</label>
<textarea className="video-text-form form-control" placeholder={"متن ویدیو"}
name={""} required="true"
// value={this.name}
// onChange={this.onChange}
onBlur={(e) => e.target.placeholder = "متن ویدیو"}
onFocus={(e) => e.target.placeholder = ""}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3 video-upload-input-btn">
<VideoUpload />
</div>
</Row>
<Row>
<div className="col-lg-6 col-12 mt-3">
<PosterUpload />
</div>
<div className="col-lg-6 col-12 mt-3">
<CoverUpload />
</div>
</Row>
</form>
{showPreview ? (
<div>
show preview
</div>
) : (<Row>
<div className="col-lg-8 col mt-3">
<button className="preview-send-data-btn" onClick={function(event){ setShowPreview(true); setShowForm(true)}}>
Preview
</button>
</div>
<div className="col-lg-4 col mt-3">
<button className="draft-send-data-btn">
Draft
</button>
</div>
</Row>)}
</div>
) : (
<div>
<button className="upload-content-btn w-100" onClick={() => setShowForm(true)}>
<span className="ml-2">
</span>New Upload </button>
</div>
)}
</div>
);
};
ReactDOM.render(<ShowOrNot />, document.getElementById("root"))
I want when click on Preview button showFrom not show and other form that in showPreview display instead. My problem is not about CSS and just I don't know how to use useState like before steps I used it.
In your example Preview inside of Form, so if you hide form preview will be hidden too.
You need to properly organize components so your code will be easy to read and understand. Without that you can not solve any complex enough task.
Can start like this.
const ShowOrNot = () => {
const [showForm, setShowForm] = useState(false);
const [showPreview, setShowPreview] = useState(false);
const [formHidden, setFormHidden] = useState(false);
return (
<div className="col-12">
{!showForm ? (
<ShowFormButton onClick={() => setShowForm(true)} />
) : undefined}
{showForm ? (
<div className={'content-send-form-wrapper'} id="scrollbar-style">
<div className={'content-send-form-header'}>
<div className={'content-send-form-header-title'}></div>
<h2>New Upload</h2>
<HideFormButton
onClick={() => {
setShowForm(false);
}}
/>
</div>
{!formHidden ? <MyForm /> : undefined}
{!showPreview ? (
<ShowPreviewButton
onClick={() => {
setShowPreview(true);
setFormHidden(true);
}}
/>
) : undefined}
{showPreview ? (
<div>
Preview
<SendButton
onClick={() => {
setFormHidden(false);
setShowPreview(false);
setShowForm(false);
}}
/>
</div>
) : undefined}
</div>
) : undefined}
</div>
);
};
function SendButton({ onClick }) {
return (
<div>
<button className=" w-100" onClick={onClick}>
<span className="ml-2"></span>Send
</button>
</div>
);
}
function ShowFormButton({ onClick }) {
return (
<div>
<button className="upload-content-btn w-100" onClick={onClick}>
<span className="ml-2"></span>New Upload{' '}
</button>
</div>
);
}
function ShowPreviewButton({ onClick }) {
return (
<Row>
<div className="col-lg-8 col mt-3">
<button className="preview-send-data-btn" onClick={onClick}>
Preview
</button>
</div>
<div className="col-lg-4 col mt-3">
<button className="draft-send-data-btn">Draft</button>
</div>
</Row>
);
}
function HideFormButton({ onClick }) {
return (
<div className={'content-send-form-close-btn'}>
<button onClick={onClick} className={'close-modal-btn'}>
<span>Close</span>
</button>
</div>
);
}
function MyForm() {
return (
<form
className={'mt-3 content-send-form-data register-teacher-inputs-box '}
>
<Row>
<div className={'col-lg-6 col-12 mt-4'}>
<label htmlFor={'name'} className={' text-right'}>
<span>*</span>
</label>
<input
type="text"
className="form-control"
placeholder={'عنوان'}
name={''}
required="true"
// value={this.name}
// onChange={this.onChange}
onBlur={(e) => (e.target.placeholder = 'عنوان')}
onFocus={(e) => (e.target.placeholder = '')}
/>
</div>
<div className={'col-lg-6 col-12 mt-4'}>
<label htmlFor={'country'} className={' text-right'}>
<span>*</span>
</label>
<input
type="text"
className="form-control"
placeholder={'دسته بندی'}
name={'country'}
// value={this.country}
// onChange={this.onChange}
required="true"
onBlur={(e) => (e.target.placeholder = 'دسته بندی')}
onFocus={(e) => (e.target.placeholder = '')}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3">
<label htmlFor={'name'} className={'label-full-size text-right'}>
<span>*</span>
</label>
<input
type="text"
className="form-control"
placeholder={'خلاصه توضیحات'}
name={''}
required="true"
// value={this.name}
// onChange={this.onChange}
onBlur={(e) => (e.target.placeholder = 'خلاصه توضیحات')}
onFocus={(e) => (e.target.placeholder = '')}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3">
<label
htmlFor={'name'}
className={'label-full-size text-right textarea-label'}
>
<span>*</span>
</label>
<textarea
className="video-text-form form-control"
placeholder={'متن ویدیو'}
name={''}
required="true"
// value={this.name}
// onChange={this.onChange}
onBlur={(e) => (e.target.placeholder = 'متن ویدیو')}
onFocus={(e) => (e.target.placeholder = '')}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3 video-upload-input-btn">
<VideoUpload />
</div>
</Row>
<Row>
<div className="col-lg-6 col-12 mt-3">
<PosterUpload />
</div>
<div className="col-lg-6 col-12 mt-3">
<CoverUpload />
</div>
</Row>
</form>
);
}
ReactDOM.render(<ShowOrNot />, document.getElementById('root'));
you should use setState like this code
setShowForm(false) or setShowForm(true)
and
setShowPreview(true) or setShowPreview(false)
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 want to fetch the image from the URL and to display it.
I take the url as input in URL text field and when I use that in img tag it works like but when I pass or use it in td background it doesn't work
import React, { Component } from 'react';
class ImageStyle extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
url: '',
summary: ''
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
render() {
return (
<div>
<div>
<h1 className="row px-2">Image Style Notification</h1>
<hr />
<div className="row px-1 py-2 animated fadeIn">
<div className="px-1" style={{ width:50 + '%' }}><br />
<div className="mb-1">
<input type="text"
className="form-control"
placeholder="Title"
name="title"
value={this.state.title}
onChange={this.handleInputChange}
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Image URL"
name="url"
value={this.state.url}
onChange={this.handleInputChange}
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Summary"
name="summary"
value={this.state.summary}
onChange={this.handleInputChange}
/>
</div>
<br />
<div className="row px-2" >
<div>
<button className="nav-link btn btn-block btn-info" onClick={this.handleClick} >Save</button>
</div>
<div className="px-1">
<button className="nav-link btn btn-block btn-danger"> Cancel</button>
</div>
</div><br />
</div>
<div><br />
<div className="mobile">
<table className="table table-clear width-css">
<tbody>
<tr>
<td backgroundImage: 'url(${this.state.url})'>
<strong>
{this.state.title}
</strong><br />
{this.state.summary}<br />
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default ImageStyle;
Specify the styles for the table and mention background image url like
backgroundImage: `url(${this.state.url})`
class ImageStyle extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
url: '',
summary: ''
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
render() {
var styles = {
backgroundImage: `url(${this.state.url})`
}
return (
<div>
<div>
<h1 className="row px-2">Image Style Notification</h1>
<hr />
<div className="row px-1 py-2 animated fadeIn">
<div className="px-1" style={{ width:50 + '%' }}><br />
<div className="mb-1">
<input type="text"
className="form-control"
placeholder="Title"
name="title"
value={this.state.title}
onChange={this.handleInputChange}
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Image URL"
name="url"
value={this.state.url}
onChange={this.handleInputChange}
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Summary"
name="summary"
value={this.state.summary}
onChange={this.handleInputChange}
/>
</div>
<br />
<div className="row px-2" >
<div>
<button className="nav-link btn btn-block btn-info" onClick={this.handleClick} >Save</button>
</div>
<div className="px-1">
<button className="nav-link btn btn-block btn-danger"> Cancel</button>
</div>
</div><br />
</div>
<div><br />
<div className="mobile">
<table className="table table-clear width-css">
<tbody>
<tr>
<td style={styles}>
<strong>
{this.state.title}
</strong><br />
{this.state.summary}<br />
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
)
}
}