How calculate the marks using switch in react? - reactjs

I created the few questions page I want calculate marks when click the submit button but when I click submit button marks didn't show.
This my code code . In this code I get the values from the checkbox and input to switch case and calculate the marks but marks doesn't show and not redirect to '/questions/markspage/${marks}' this page.
code
function InAnswers() {
const history = useHistory();
const [answers, setAnswers] = useState('');
const [question, setQuestion] = useState('');
const [dayWord, setDayWord] = useState(''); //1
const [seeObject, setSeeObject] = useState(''); //2
const [identifyObject, setIdentifyObject] = useState(''); //3
const [identifyColor, setIdentifyColor] = useState(''); //4
const [firstWord, setFirstWord] = useState(''); //5
const [marks, setMarks] = useState(''); //5
async function submitMarks(event) {
event.preventDefault();
var marks = 0;
switch (marks) {
case 'wordday' == 'wordmore5':
setMarks(marks + 10);
return setMarks;
break;
case 'see' == 'yessee ':
setMarks(marks + 10);
return setMarks;
break;
case 'identify' == 'yesidentify':
setMarks(marks + 10);
return setMarks;
break;
case 'colors' == 'colorsyes ':
setMarks(marks + 10);
return setMarks;
break;
case 'firstword' == 'firstword18 ':
setMarks(marks + 10);
return setMarks;
break;
default:
setMarks(marks + 10);
return setMarks;
history.push(`/questions/markspage/${marks}`);
}
}
// // calculate marks
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<div className='pb-2 px-3 d-flex flex-wrap align-items-center justify-content-between'>
<h2>Questions </h2>
</div>
</div>
<div className='col-3'></div>
</div>
{/* </div> */}
<div className='row'>
<h4 className='mb-4'> Questions </h4>
<form onSubmit={submitMarks}>
<div>
<div className='progressCard'>
<div className='p-3'>
<h2>1. how many words child talk in a day?</h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='wordday'
id='wordless5'
value='wordless5'
onChange={(e) => setDayWord(e.target.value)}
/>
<label className='form-check-label' for='wordless5'>
less 5
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='wordday'
id='wordmore5'
value='wordmore5'
onChange={(e) => setDayWord(e.target.value)}
/>
<label className='form-check-label' for='wordmore5'>
more than 5
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
<br></br>
<div className='progressCard'>
<div className='p-3'>
<h2>
2. when you show some thing to child then is child watch
there?
</h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='see'
id='nosee'
value='nosee'
required
onChange={(e) => setSeeObject(e.target.value)}
/>
<label className='form-check-label' for='PUBLISH'>
no
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='see'
id='yessee'
value='yessee'
required
onChange={(e) => setSeeObject(e.target.value)}
/>
<label className='form-check-label' for='UNPUBLISH'>
yes
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
<br></br>
<div className='progressCard'>
<div className='p-3'>
<h2>3.When you show some thing then is child identify that </h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='identify'
id='noidentify'
value='noidentify'
required
onChange={(e) => setIdentifyObject(e.target.value)}
/>
<label className='form-check-label' for='PUBLISH'>
no
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='identify'
id='yesidentify'
value='yesidentify'
required
onChange={(e) => setIdentifyObject(e.target.value)}
/>
<label className='form-check-label' for='UNPUBLISH'>
yes
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
<br></br>
<div className='progressCard'>
<div className='p-3'>
<h2>4. child can identify more than 5 colors</h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='colors'
id='colorsno'
value='colorsno'
required
onChange={(e) => setDayWord(e.target.value)}
/>
<label className='form-check-label' for='PUBLISH'>
no
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='colors'
id='colorsyes'
value='colorsyes'
required
onChange={(e) => setDayWord(e.target.value)}
/>
<label className='form-check-label' for='UNPUBLISH'>
yes
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
<br></br>
<div className='progressCard'>
<div className='p-3'>
<h2>5.The first word child told?</h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='firstword'
id='firstword19'
value='firstword19'
required
onChange={(e) => setFirstWord(e.target.value)}
/>
<label className='form-check-label' for='firstword19'>
after 18 months
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='firstword'
id='firstword18'
value='firstword18'
required
onChange={(e) => setFirstWord(e.target.value)}
/>
<label className='form-check-label' for='firstword18'>
before 18 months
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
</div>
</form>
<div className='col-xl-6 mb-4'></div>
<div>
<input
type='submit'
value='SUBMIT ANSWERS '
className='form-submit-btn'
/>
</div>
</div>
</div>
);
}
export default InAnswers;

You should define the submit input inside the <form> tag:
<form onSubmit={submitMarks}>
...
<div className='col-xl-6 mb-4'></div>
<div>
<input
type='submit'
value='SUBMIT ANSWERS '
className='form-submit-btn'
/>
</div>
</form>
If you need to calculate the total for marks given the responses you should rewrite the submitMarks function as:
function submitMarks(event) {
event.preventDefault();
var marks = 0;
if (dayWord === 'wordmore5') marks += 10;
if (seeObject === 'yessee') marks += 10;
if (identifyObject === 'yesidentify') marks += 10;
if (identifyColor === 'colorsyes') marks += 10;
if (firstWord === 'firstword18') marks += 10;
history.push(`/questions/markspage/${marks}`);
}
No need to declare it async nor declare a separate marks state variable.

Related

radio input still true after unchecked

I have filter section with checkbox and radio when user unchecked for checkbox the content is hidding, but for radio I can't hidden the content he still true.
Any help please
const inputChecked = (e) => {
const updatedList = [...checked];
if (e.target.checked) {
updatedList = [...checked, e.target.value];
}
else {
updatedList.splice(checked.indexOf(e.target.value),1)
}
setChecked(updatedList);
};
return (
<form>
<div onChange={inputChecked}>
<div className='flex items-center'>
<input type='radio' id="most_recent" name="sort_by" value='Most recent' />
<label htmlFor='most_recent'>Most recent</label>
</div>
<div className='flex items-center'>
<input type='radio' id="most_relevent" name="sort_by" value='Most relevent' />
<label htmlFor='most_relevent'>Most relevent</label>
</div>
</div>
<div onChange={inputChecked}>
<div className='flex items-center'>
<input type='checkbox' id="intership" name="intership" value='intership' />
<label htmlFor='intership'>intership</label>
</div>
<div className='flex items-center'>
<input type='checkbox' id="Director" name="director" value='Director' />
<label htmlFor='Director'>Director</label>
</div>
<div className='flex items-center'>
<input type='checkbox' id="Associate" name="associate" value='Associate' />
<label htmlFor='Associate'>Associate</label>
</div>
</div>
</form>
)
Separate into two types of handle: handle for radio checked and handle for checkbox checked.
Have to put onChange into each radio input <input type="radio" onChange={}... />. Try this below code:
const [prevRadio, setPrevRadio] = useState("")
const radioChecked = (e) => {
setPrevRadio(e.target.value)
let updatedList = [...checked, e.target.value];
updatedList.splice((prevRadio ? checked.indexOf(prevRadio) : (checked.length + 99)),1)
setChecked(updatedList)
}
const inputChecked = (e) => {
let updatedList = [...checked];
if (e.target.checked) {
updatedList = [...checked, e.target.value];
}
else {
updatedList.splice(checked.indexOf(e.target.value),1)
}
setChecked(updatedList);
};
return (
<form>
<div>
<div className='flex items-center'>
<input type='radio' id="most_recent" name="sort_by" value='Most recent'
onChange={inputChecked}/> //<== Put onChange in here
<label htmlFor='most_recent'>Most recent</label>
</div>
<div className='flex items-center'>
<input type='radio' id="most_relevent" name="sort_by" value='Most relevent'
onChange={inputChecked}/> //<== Put onChange in here
<label htmlFor='most_relevent'>Most relevent</label>
</div>
</div>
<div onChange={inputChecked}>
<div className='flex items-center'>
<input type='checkbox' id="intership" name="intership" value='intership' />
<label htmlFor='intership'>intership</label>
</div>
<div className='flex items-center'>
<input type='checkbox' id="Director" name="director" value='Director' />
<label htmlFor='Director'>Director</label>
</div>
<div className='flex items-center'>
<input type='checkbox' id="Associate" name="associate" value='Associate' />
<label htmlFor='Associate'>Associate</label>
</div>
</div>
</form>
)

how can i edit the value of add multiple dynamic form in react class?

I'm working on dynamic react form. I want to update dynamic form data. I have populate and get the data from backend successfully but when I enter in input field for change some data then I'm not able to change it. I am adding here my form image. Please check and tell me how can I can fix it.
import React from "react"
const VarientDetailEdit = (props) => {
return (
props.varientDetails.map((val, idx) => {
let sort=`sort-${idx}`, sku=`sku-${idx}`, waightunitno=`waightunitno-${idx}`, unit=`unit-${idx}`, mrp=`mrp-${idx}`, discount=`discount-${idx}`, price=`price-${idx}`, stock=`stock-${idx}`, minstock=`minstock-${idx}`, outofstock=`outofstock-${idx}`
return (
<div>
<div style={{float:"right"}}>
{
idx ?
<button style={{paddingLeft:"10px"}} className="btn btn-danger" onClick={(() => props.delete(val))} ><i className="fa fa-minus" aria-hidden="true"></i></button> : null
}
</div>
<div><br></br><br></br>
<div key={val.index} className='row'>
<div class="form-group col-sm-4">
<label>Sort:</label>
<input type="text" value={val.sort} name="sort" data-id={idx} id={sort} className="form-control " />
</div>
<div class="form-group col-sm-4">
<label>SKU</label>
<input type="text" value={val.sku} name="sku" data-id={idx} id={sku} className="form-control " />
</div>
<div class="form-group col-sm-4">
<label>Weight/Quantity</label>
<input type="text" value={val.waightunitno} name="waightunitno" id={waightunitno} data-id={idx} className="form-control " />
</div>
</div>
<div className='row'>
<div class="form-group col-sm-4">
<label>Unit</label>
<input type="text" value={val.unit} name="unit" id={unit} data-id={idx} className="form-control " />
</div>
<div class="form-group col-sm-4">
<label>MRP <em style={{color:"tomato"}}>*</em></label>
<input type="text" value={val.mrp} name="mrp" id={mrp} data-id={idx} className="form-control " />
</div>
<div class="form-group col-sm-4">
<label>Discount(%) <em style={{color:"tomato"}}>*</em></label>
<input type="text" value={val.discount} name="discount" id={discount} data-id={idx} className="form-control " />
</div>
</div>
<div className='row'>
<div class="form-group col-sm-4">
<label>Price <em style={{color:"tomato"}}>*</em></label>
<input type="text" value={val.price} name="price" id={price} data-id={idx} className="form-control " />
</div>
<div class="form-group col-sm-4">
<label>Stock <em style={{color:"tomato"}}>*</em></label>
<input type="text" value={val.stock} name="stock" id={stock} data-id={idx} className="form-control " />
</div>
<div class="form-group col-sm-4">
<label>Min Stock Alert <em style={{color:"tomato"}}>*</em></label>
<input type="text" value={val.minstock} name="minstock" id={minstock} data-id={idx} className="form-control " />
</div>
<div className='col-sm-4'>
<div className="form-group">
<label className="form-label">Variant Out of Stock Status <em style={{color:"tomato"}}>*</em></label>
<select name="outofstock" value={val.outofstock} id={outofstock} data-id={idx} className="form-control" >
<option value="pending">Pending</option>
<option value="In Progress">In progress</option>
<option value="Completed">Completed</option>
<option value="Hold">Hold</option>
</select>
</div>
</div>
<hr className="my-4"></hr>
</div>
</div>
</div>
)
})
)
}
export default VarientDetailEdit
Parent component
handleChange = (e) => {
if (["sort", "sku", "waightunitno", "unit", "mrp", "discount", "price", "stock", "minstock", "outofstock"].includes(e.target.name)) {
let varientDetails = [...this.state.varientDetails]
varientDetails[e.target.dataset.id][e.target.name] = e.target.value;
} else if (["isTex"].includes(e.target.name)) {
this.setState({ [e.target.name]: e.target.value })
console.log(e)
// }else if (["files[]"].includes(e.target.name)) {
// this.setState({ files:e.target.files });
}
else {
this.setState({ [e.target.name]: e.target.value })
}
}
addNewRow = () => {
this.setState((prevState) => ({
varientDetails: [...prevState.varientDetails, { index: Math.random(), sort:5,
sku: "",
waightunitno: "",
unit:"",
mrp:0,
discount:0,
price:0,
stock:0,
minstock:0,
outofstock:""}],
}));
}
deteteRow = (index) => {
this.setState({
varientDetails: this.state.varientDetails.filter((s, sindex) => index !== sindex),
});
}
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state)
if(this.state.date==='' || this.state.description==='')
{
NotificationManager.error(" Error -Please Fill up all Required Field!!!");
return false;
}
for(var i=0;i<this.state.varientDetails.length;i++)
{
if(this.state.varientDetails[i].sort==='' || this.state.varientDetails[i].varient==='')
{
NotificationManager.error("Error- Product Varient Fields are required!!!");
return false;
}
}
const formData = new FormData();
for (const file of this.state.files) {
formData.append('file', file)
}
const config = {
Headers: {
'content-type': 'multipart/form-data',
"Content-Type": "multipart/form-data; boundary=AaB03x" +
"--AaB03x" +
"Content-Disposition: file" +
"Content-Type: png" +
"Content-Transfer-Encoding: binary" +
"...data... " +
"--AaB03x--",
"Accept": "application/json",
"type": "formData"
},
productId:this.state.id,
name:this.state.name,
description:this.state.description,
lableType:this.state.lableType,
photo:this.state.thumbNailphoto,
isTex:this.state.isTex,
GSTrate:this.state.GSTrate,
GSTtyp:this.state.GSTtyp,
HSNcode:this.state.HSNcode,
videoUpload:this.state.videoUpload,
// categoryId:this.state.categoryId,
// subCategoryId:this.state.subCategoryId,
tags:this.state.tags,
file:formData,
reccomendedProduct:this.state.reccomendedProduct,
varientDetails:this.state.varientDetails
};
console.log(this.state)
swal({
title: "Are you sure?",
text: "You want to Add New Product",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then(async (success) => {
if (success) {
let list = await GetProductDetails.getUpdateProduct(config);
if (list) {
this.setState({ isLoaded: false })
this.props.history.push("/admin/mainproduct/list")
} else {
NotificationManager.error("Please! Check input field", "Input Field");
}
}
});
}
clickOnDelete(record) {
this.setState({
varientDetails: this.state.varientDetails.filter(r => r !== record)
});
}
render() {
let { varientDetails,subCategoryId,files,updateFile,loading,productphotos,categoryId,reccomendedProduct } = this.state//let { notes, date, description, varientDetails } = this.state
console.log(updateFile)
return (
<div className="container-fluid">
<div className="row">
<div className="col-lg-5 col-md-9 col-lg-6">
<h2 className="mt-30 page-title">Products</h2>
</div>
<div className="col-lg-5 col-md-3 col-lg-6 back-btn">
<button className='btntop btn text-light' onClick={(e) => this.handleBack()}><i className="fas fa-arrow-left" />cancle</button>
<button type="submit" onClick={this.handleSubmit} className='btntop btn text-light mx-2'>Add</button>
</div>
</div>
<ol className="breadcrumb mb-30">
<li className="breadcrumb-item">Dashboard</li>
<li className="breadcrumb-item">Products</li>
<li className="breadcrumb-item active">Edit Product</li>
</ol>
<hr></hr>
<div className='container'>
<form onChange={this.handleChange} >
<div className='row'>
<div className='col-sm-8'>
<div className='row'>
<div className='col-sm-8'>
<div className="form-group">
<label htmlFor="name" class="form-label">Title <em style={{ color: "tomato" }}>*</em></label>
<input type="text" id="name" value={this.state.name} name="name" class=" w3-input w3-border form-control" aria-describedby="passwordHelpBlock" />
</div>
</div>
<div className="col-lg-12 col-md-12">
<div className="form-group">
<label className="form-label">Description*</label>
<RichTextEditor
style={{ height: " 275.438px" }}
className="w3-input w3-border"
content={this.state.description}
handleContentChange={this.handleContentChange}
placeholder="insert text here..." />
</div>
</div>
<div className='col-sm-8 py-4'>
<div className="form-group row">
<label className="my-2">Lables</label>
<label className="btn opt mx-2 col-2 active"style={{backgroundColor: "blue",borderColor: "#449D44"}}>
<input type="radio" id="lableType" hidden name="lableType" autocomplete="off" checked="checked"/> None
</label>
<label className="btn opt col-2 mx-2"style={{backgroundColor: "#449D44",borderColor: "#449D44"}}>
<input type="radio" hidden id="lableType" name="lableType" value="veg" autocomplete="off" checked="checked"/> veg
</label>
<label className="btn opt mx-2 col-3" style={{backgroundColor: "#C9302C",borderColor: "#C9302C"}}>
<input type="radio" hidden id="lableType" name="lableType" value="None Veg" autocomplete="off" checked="checked"/> None Veg
</label>
</div>
</div>
<div className='col-sm-12'>
<div className="form-group">
<label htmlFor="inputPassword5" class="form-label">Tags</label>
{/* <input type="text" id="inputPassword5" class="w3-input w3-border form-control" aria-describedby="passwordHelpBlock"/> */}
<TagsEditor setStateOfTags={this.setStateOfTags} />
</div>
</div><br></br>
<div className='col py-4'>
<div className="form-group">
<input type="checkbox" name="isTex"value={this.state.isTex} id="isTex" data-toggle="switchbutton" checked data-onlabel="true" data-offlabel="false" data-onstyle="success" data-offstyle="danger" />
</div>
<label htmlFor="isTex" class="form-label">is Taxt Enable</label>
</div>
<div className='row'>
<div className='col-sm-4'>
<div className="form-group">
<label className="form-label">GST Rate<em style={{ color: "tomato" }}>*</em></label>
<input type="number" value={this.state.GSTrate} className=" w3-input w3-border form-control" name="GSTrate" id="GSTrate" />
</div>
</div>
<div className='col-sm-4'>
<div className="form-group">
<label className="form-label">GST Rate Type <em style={{ color: "tomato" }}>*</em></label>
<select id="GSTtyp" value={this.state.GSTtyp} name="GSTtyp" className=" w3-input w3-border form-control">
<option value={1}>Inclusive</option>
<option value={0}>Exclusive</option>
</select>
</div>
</div>
</div>
<div className='col-sm-4 py-2'>
<div className="form-group">
<label htmlFor="HSNcode" class="form-label">HSN Code</label>
<input type="text" value={this.state.HSNcode} name="HSNcode" className='w3-input w3-border form-control' id="HSNcode" aria-describedby="passwordHelpBlock" />
</div>
</div><br></br>
</div>
{/* now we are using varient dynamic form */}
<div className='varientheader py-4' style={{ paddingBottom: "15px" }}>
<a onClick={this.addNewRow} className="btn" style={{ float: 'right', color: "Tomato" }}><i class="fas fa-plus"></i>Add More</a>
<h3 style={{ float: 'left', }}>Varients</h3>
</div>
<hr style={{ padding: "2px", border: "2 px solid black" }}></hr>
<div className="container py-4" style={{ border: "lightgray" }}>
<VarientDetailEdit add={this.addNewRow} delete={this.clickOnDelete.bind(this)} varientDetails={varientDetails} />
</div>
<div className='recomended product'>
<hr></hr>
<h3>Recommended Products</h3>
<hr></hr>
<div className='ex1'>
<ReccomendedFormList rowRcData={reccomendedProduct} setStaterecomended={this.setStaterecomended} />
</div>
</div>
</div>
{/* right section cotegory */}
<div className='col-sm-4'>
<div>
<h3>Category <em style={{ color: "tomato" }}>*</em></h3>
<div className='mx-4 my-2'>
<div className='categorycontainer'>
<CategoryListEdit data={categoryId} sdata={subCategoryId} setStateOfCategory={this.setStateOfCategory} />
<hr></hr>
</div>
{/* file upload */}
<div className='imagecontainer'>
<h3>Upload Images</h3>
<hr />
<div className="wrapper">
<div className="drop">
<div className="cont">
<i className="fas fa-cloud-upload-alt"></i>
<div className="tit">
Drag & Drop
</div>
<div className="desc">
your files to Assets, or
</div>
<div className="browse">
click here to browse
</div>
</div>
<input id="files" multiple name="files[]" onChange={this.fileSelectedHandler} type="file" />
</div>
<ToastContainer autoClose={1500} />
</div>
{this.state.filselected ? <div><i>{this.state.filselected}</i>
{/* <div className="form-group">
<button className="save-btn hover-btn" type="submit" onClick={this.handleSubmitPhoto} disabled={loading}>
{loading && <i className="fa fa-refresh fa-spin" />}
{loading && <span>Upload</span>}
{!loading && <span>Upload</span>}
</button>
<ToastContainer autoClose={1500} />
</div> */}
</div>:
<p>Drag & Drop files here or click to browse.
Note: Max 4 images are allowed.</p>
}
<div style={{display:"flex",margin:"10px"}} >
{ productphotos.map((item,i)=>(
<div className="img_wrp mx-2">
<img width="60px" height="55px" value ={item.imgUrl} src={item.imgUrl} alt="video not found "/><i onClick={(e) =>this.handlawsDeleteById(item.id,item.imgUrl)} className="fa fa-close close"></i>
</div>
))}
</div>
<hr></hr>
</div>
<div className='uploadfile'>
<h3>Upload Video </h3>
<input type="file" className="form-control" onChange={this.VideoUploadFile} />
<p style={{ color: "blue",fontStyle:"italic",fontWeight:"bold" }}>{this.state.msgvideoUpload}</p>
<div className="img_wrp">
<img width="200px" height="150px" src={this.state.videoUpload} alt="video not found "/><i onClick={this.deletePhotoStaticVideo} className="fa fa-close close"></i>
</div>
{/* { this.state.uploadPercentage > 0 && <ProgressBar variant="danger" now={this.state.uploadPercentage} active label={`${this.state.uploadPercentage}%`} /> }<br></br> */}
<div className='upload thambnail my-4'>
<h3>Video Thumbnail Image</h3>
<div className="file-area">
<div className="form-group">
<input type="file" className="form-control" onChange={this.ThumbnainVideoUpload} />
<div className="file-dummy">
<i className="fas fa-plus mx-4 my-4"></i><br></br>
<span className="default">Click to select a file, or drag it here</span>
<span className="success">Great, your file is selected</span>
</div>
<p style={{ color: "blue",fontStyle:"italic",fontWeight:"bold" }}>{this.state.msgThumb}</p>
<div className="img_wrp">
<img width="200px" height="150px" src={this.state.thumbNailphoto} alt="thumbnail not found"/><i className="fa fa-close close" onClick={this.deletePhotoStaticThumb} ></i>
</div>
{/* {(() => {
if (!this.state.photo)
return <button onClick={this.handleCanclePhoto}>delete</button>
}
)} */}
{/* { this.state.uploadPercentage > 0 && <ProgressBar variant="danger" now={this.state.uploadPercentage} active label={`${this.state.uploadPercentage}%`} /> }<br></br> */}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
)
}
i have solve my problem.we have to use defaultValue for solve his problem
<input type="text" defaultValue={this.props.value || ''} />

Changing state in useEffect

I am dispatching an action in useEffect hook to fetch data and then updating state using the data from redux store. When the page first loads i get the correct data, but when refreshing the browser I get undefined values.
React.useEffect(() => {
dispatch(getSingleCoin(props.match.params.id))
setName(coinDetail.name)
setSymbol(coinDetail.symbol)
setLogourl(coinDetail.logo)
setPrice(coinDetail.price)
setLaunchDate(coinDetail.launchDate)
setWebsiteUrl(coinDetail.websiteUrl)
setNetwork(coinDetail.chain)
setAddress(coinDetail.address)
setTwitterUrl(coinDetail.twitter)
setTelegramUrl(coinDetail.telegram)
setRedditUrl(coinDetail.reddit)
setYoutubeUrl(coinDetail.youtube)
setCoinDescription(coinDetail.description)
setMarketCap(coinDetail.marketCap)
}
}, [coinDetail,dispatch, props.match.params.id])
const handleSubmit = (e) => {
e.preventDefault()
const coin = {}
coin.name = name
coin.symbol = symbol
coin.logo = logourl
coin.price = price
coin.launchDate = launchDate
coin.websiteUrl = websiteUrl
coin.chain = network
coin.address = address
coin.twitter = twitterUrl
coin.telegram = telegramUrl
coin.reddit = redditUrl
coin.youtube = youtube
coin.description = coinDescription
coin.marketCap = marketCap
coin._id = props.match.params.id
dispatch(updateCoin(coin))
}
return (
<div className="container add-coin-wapper mt-4">
{loading && coinDetail === undefined ? (
<div>...Loading</div>
) : error ? (
<div>{error}</div>
) : (
<div className="card ">
<div className="card-header">
<div className="approve-header">
<div
className="approve-back"
onClick={() => props.history.push('/Admin/coinlist')}
>
<ArrowBackIosIcon />
<div>Back to Coin listing</div>
</div>
</div>
</div>
<div className="card-body">
{/* here */}
<>
<div>
<h3>Edit Coin</h3>
</div>
<form onSubmit={handleSubmit}>
<div className="row">
<div className="col-sm-12 col-md-6 col-lg-6">
<h5>Coin informations</h5>
<div className="form-group">
<label htmlFor="name">name</label>
<input
type="text"
className="form-control"
id="name"
name="name"
placeholder="Bitcoin"
required
onChange={(e) => setName(e.target.value)}
value={name}
/>
</div>
<div className="form-group">
<label htmlFor="symbol">symbol</label>
<input
type="text"
className="form-control"
id="symbol"
name="symbol"
placeholder="Enter symbol"
onChange={(e) => setSymbol(e.target.value)}
required
value={symbol}
/>
</div>
<div className="form-group">
<label htmlFor="logo">Logo url</label>
<input
type="text"
className="form-control"
id="url"
name="logourl"
placeholder="https://clod.com/logo"
onChange={(e) => setLogourl(e.target.value)}
value={logourl}
/>
</div>
<div className="form-group">
<label htmlFor="description">Coin Description</label>
<textarea
className="form-control"
id="exampleFormControlTextarea1"
rows="3"
onChange={(e) => setCoinDescription(e.target.value)}
placeholder="Describe your coin appropriately to show attractiveness"
value={coinDescription}
></textarea>
</div>
<div className="form-group">
<label htmlFor="price">price</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">$</div>
</div>
<input
type="number"
className="form-control"
id="marketcap"
placeholder="0.00085"
step="any"
min="0"
onChange={(e) => setPrice(e.target.value)}
value={price}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="marketcap">Market cap</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">$</div>
</div>
<input
type="number"
className="form-control"
id="marketcap"
step="any"
placeholder="0.00085"
min="0"
onChange={(e) => setMarketCap(e.target.value)}
value={marketCap}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="launchdate">Launch date</label>
<div
className="input-group date"
data-provide="datepicker"
>
<input
type="date"
className="form-control"
onChange={(e) => setLaunchDate(e.target.value)}
value={moment(launchDate).format('YYYY-MM-DD')}
/>
<div className="input-group-addon">
<span className="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
</div>
<div className="col-sm-12 col-md-6 col-lg-6">
<h5>Coin market</h5>
<div className="form-group">
<label htmlFor="network">Network/Chain</label>
<select
className="form-control"
id="network"
onChange={(e) => setNetwork(e.target.value)}
value={network}
>
<option value="BSC">Binance Smart Chain (BSC)</option>
<option value="ETH">Ethereum (ETH)</option>
<option value="SOL">Solona (SOL)</option>
</select>
</div>
<div className="form-group">
<label htmlFor="contract">Contract Adress</label>
<input
type="text"
className="form-control"
id="contract"
name="contract"
placeholder="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
onChange={(e) => setAddress(e.target.value)}
required
value={address}
/>
</div>
<h5>Coin links</h5>
<div className="form-group">
<label htmlFor="weburl">Website url</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<LanguageIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="web"
placeholder="https://www.coinx.com"
onChange={(e) => setWebsiteUrl(e.target.value)}
required
value={websiteUrl}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="twitter">Twitter</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<TwitterIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="twitter"
placeholder="https://twitter.com/"
onChange={(e) => setTwitterUrl(e.target.value)}
value={twitterUrl}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="telegram">Telegram</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<TelegramIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="telegram"
placeholder="https://t.me/"
onChange={(e) => setTelegramUrl(e.target.value)}
value={telegramUrl}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="youtube">YouTube</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<YouTubeIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="youtube"
placeholder="https://www.youtube.com/watch?v="
onChange={(e) => setYoutubeUrl(e.target.value)}
value={youtube}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="reddit">Reddit</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<RedditIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="reddit"
placeholder="https://www.reddit.com"
onChange={(e) => setRedditUrl(e.target.value)}
value={redditUrl}
/>
</div>
</div>
<button type="submit" className="btn" disabled={loading}>
update
</button>
</div>
</div>
</form>
</>
{/* here */}
</div>
{/* here */}
</div>
)}
</div>
The state data is supposed to be displayed in form input elements. I render a div with a loading status before the data is fetched and loading set to false.

How can I export a variable to another file React

I am doing a program which gets information from the https://api.randomuser.me/ API. I got the fetch call working but my goal is to display the information as prefilled information in a form located in another file, but I don't know how I should export the variables and how to use them in the other file.
This is my FetchCall.js:
import Axios from 'axios'
import { useState } from 'react';
function FetchCall() {
const[name,setName] = useState("")
const[birth,setBirth] = useState("")
const[email,setEmail] = useState("")
const[insuranceNo, setInsuranceNo] = useState("")
const[phoneNo, setPhoneNo] = useState("")
const getInfo = () => {
Axios.get("https://api.randomuser.me/").then(
(response) => {
setName(response.data.results[0].name.first + " " + response.data.results[0].name.last);
setBirth(response.data.results[0].dob.date);
setEmail(response.data.results[0].email)
setInsuranceNo(response.data.results[0].login.sha1)
setPhoneNo(response.data.results[0].phone)
}
);
};
return(
<div>
Hello
<button onClick={getInfo}>Get User</button>
<div>
{name}
</div>
<div>
{birth}
</div>
<div>
{email}
</div>
<div>
{insuranceNo}
</div>
<div>
{phoneNo}
</div>
</div>
);
}
export default FetchCall;
And here is where I want to export the variables (name, birth,email, insuranceNo,phoneNo)
import FetchCall from './fetchCall';
function InputTextFilled() {
return (
<div className="inputText has-text-left">
<fieldset disabled>
<div className="field">
<div className="control">
<p className="label">Full Name</p>
<input className="input" type="text" value="VARIABLEHERE" />
</div>
<div className="control mt-5">
<a className="label">Date of Birth</a>
<input className="input" type="text" value="VARIABLEHERE" />
</div>
<div className="control mt-5">
<p className="label">National Insurance Number</p>
<input className="input" type="text" value="VARIABLEHERE" />
</div>
<div className="control mt-5">
<p className="label">Email Address</p>
<input className="input" type="text" value="VARIABLEHERE" />
</div>
<div className="control mt-5">
<p className="label">Telephone Number</p>
<input className="input" type="text" value="VARIABLEHERE" />
</div>
</div>
</fieldset>
</div>
);
}
export default InputTextFilled;
React Props are like function arguments in JavaScript and attributes in HTML.
To send props into a component, use the same syntax as HTML attributes.
import Axios from "axios";
import { useState } from "react";
function FetchCall() {
const [name, setName] = useState("");
const [birth, setBirth] = useState("");
const [email, setEmail] = useState("");
const [insuranceNo, setInsuranceNo] = useState("");
const [phoneNo, setPhoneNo] = useState("");
const getInfo = () => {
Axios.get("https://api.randomuser.me/").then((response) => {
setName(
response.data.results[0].name.first +
" " +
response.data.results[0].name.last
);
setBirth(response.data.results[0].dob.date);
setEmail(response.data.results[0].email);
setInsuranceNo(response.data.results[0].login.sha1);
setPhoneNo(response.data.results[0].phone);
});
};
return (
<div>
Hello
<button onClick={getInfo}>Get User</button>
<div>{name}</div>
<div>{birth}</div>
<div>{email}</div>
<div>{insuranceNo}</div>
<div>{phoneNo}</div>
{/* //This is the child compoennt */}
<DisplayExample1
name={name}
birth={birth}
email={email}
insuranceNo={insuranceNo}
phoneNo={phoneNo}
/>
<DisplayExample2
name={name}
birth={birth}
email={email}
insuranceNo={insuranceNo}
phoneNo={phoneNo}
/>
</div>
);
}
export default FetchCall;
In a functional stateless component, the props are received in the function signature as arguments:
//Child Component Example 1
const DisplayExample1 = ({ name, birth, insuranceNo, phoneNo }) => (
<div className="inputText has-text-left">
<fieldset disabled>
<div className="field">
<div className="control">
<p className="label">Full Name</p>
<input className="input" type="text" value={name} />
</div>
<div className="control mt-5">
<a className="label">Date of Birth</a>
<input className="input" type="text" value={birth} />
</div>
<div className="control mt-5">
<p className="label">National Insurance Number</p>
<input className="input" type="text" value={insuranceNo} />
</div>
<div className="control mt-5">
<p className="label">Email Address</p>
<input className="input" type="text" value={email} />
</div>
<div className="control mt-5">
<p className="label">Telephone Number</p>
<input className="input" type="text" value={phoneNo} />
</div>
</div>
</fieldset>
</div>
);
React's props can pass data in React by defining custom HTML attributes to which you assign your data with JSX syntax. So don't forget the curly braces.
//Child Component Example 2 (Class Component)
class DisplayExample2 extends Component {
render() {
return (
<div className="inputText has-text-left">
<fieldset disabled>
<div className="field">
<div className="control">
<p className="label">Full Name</p>
<input className="input" type="text" value={this.props.name} />
</div>
<div className="control mt-5">
<a className="label">Date of Birth</a>
<input className="input" type="text" value={this.props.birth} />
</div>
<div className="control mt-5">
<p className="label">National Insurance Number</p>
<input
className="input"
type="text"
value={this.props.insuranceNo}
/>
</div>
<div className="control mt-5">
<p className="label">Email Address</p>
<input className="input" type="text" value={this.props.email} />
</div>
<div className="control mt-5">
<p className="label">Telephone Number</p>
<input className="input" type="text" value={this.props.phoneNo} />
</div>
</div>
</fieldset>
</div>
);
}
}

Return a message for a search display zero search results in react hooks

If a search in React hooks has returned zero results, I would like to display a text message "No data available for the search criteria !" in the page ? I have tried a condition, but not sure where to add.
if(results.length == 0) {
return (
<div>No data available for the search criteria !</div>
)
}
const [searchTerm, setSearchTerm] = useState("");
const [searchResults, setSearchResults] = useState([]);
const handleChange = event => {
setSearchTerm(event.target.value);
};
useEffect(() => {
const results = playerList.filter(player =>
player.name.toLowerCase().includes(searchTerm) || player.name.toUpperCase().includes(searchTerm) || player.position.toLowerCase().includes(searchTerm)
|| player.position.toUpperCase().includes(searchTerm)
);
setSearchResults(results);
}, [searchTerm]);
//
return (
<div className="App">
<label>
<div className="playerSearch_Home">
<div className="playerSearch_Icon">
<img src="/images/search-image-player.jpg"></img>
</div>
<input type="text" className="playerSearch_Home_Input" placeholder="Search players..." value={searchTerm} onChange={handleChange} />
</div>
</label>
<div className="playerList_home_page">
<div className="grid-container">
{
searchResults.map(player => {
return (
<div className="grid-item">
<div>
<img className="playerProfilePic_home_tile" key={player.image} src={player.image}></img>
</div>
<div className="playerProfile_grid_border">
<h3 key={player.name}>{player.name}</h3>
<span className="playerPosition_home_tile" key={player.position}>{player.position}</span>
</div>
</div>
);
})
}
</div>
</div>
</div>
);
You use simply ternary operator, something like this :
{
searchResults.length ?
searchResults.map(player => {
return (
<div className="grid-item">
<div>
<img className="playerProfilePic_home_tile" key={player.image} src={player.image}></img>
</div>
<div className="playerProfile_grid_border">
<h3 key={player.name}>{player.name}</h3>
<span className="playerPosition_home_tile" key={player.position}>{player.position}</span>
</div>
</div>
);
}) :
"No data available for the search criteria !"
}
You can use ternary operator based on the length of searchResults.
Please check the code below:
return (
<div className="App">
<label>
<div className="playerSearch_Home">
<div className="playerSearch_Icon">
<img src="/images/search-image-player.jpg"></img>
</div>
<input type="text" className="playerSearch_Home_Input" placeholder="Search players..." value={searchTerm} onChange={handleChange} />
</div>
</label>
<div className="playerList_home_page">
<div className="grid-container">
{
**searchResults.length > 0 ?**
searchResults.map(player => {
return (
<div className="grid-item">
<div>
<img className="playerProfilePic_home_tile" key={player.image} src={player.image}></img>
</div>
<div className="playerProfile_grid_border">
<h3 key={player.name}>{player.name}</h3>
<span className="playerPosition_home_tile" key={player.position}>{player.position}</span>
</div>
</div>
);
})
**} : <p>Zero records found for the Search</p>**
</div>
</div>
</div>
);
You need to make a conditional render based on the length of the search results array. If there's nothing in the array, then it will show a message.
{!searchResults.length && (<div> <p> No data available for the search criteria ! </p> </div>) }
return (
<div className="App">
<label>
<div className="playerSearch_Home">
<div className="playerSearch_Icon">
<img src="/images/search-image-player.jpg"></img>
</div>
<input type="text" className="playerSearch_Home_Input" placeholder="Search players..." value={searchTerm} onChange={handleChange} />
</div>
</label>
{!searchResults.length && (<div> <p> No data available for the search criteria ! </p> </div>) }
<div className="playerList_home_page">
<div className="grid-container">
{
searchResults.map(player => {
return (
<div className="grid-item">
<div>
<img className="playerProfilePic_home_tile" key={player.image} src={player.image}></img>
</div>
<div className="playerProfile_grid_border">
<h3 key={player.name}>{player.name}</h3>
<span className="playerPosition_home_tile" key={player.position}>{player.position}</span>
</div>
</div>
);
})
}
</div>
</div>
</div>
);

Resources