Boolean checkbox value in JSX doesn't work - javascript

IU'm using a github code example and that works perfectly with text inputs & numbers, but when I want to use checkbox inputs, the application doesn't understand the values and returns null or just on values...
Any idea why this doesn't work on fEdit function?
import React, { Component } from "react";
// import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
title: "React Simple CRUD Application",
act: 0,
index: "",
datas: []
};
}
componentDidMount() {
this.refs.name.focus();
}
handleChange = e => {
console.log(e.target.value);
};
fSubmit = e => {
e.preventDefault();
console.log("try");
let datas = this.state.datas;
let name = this.refs.name.value;
let isenable = this.refs.isenable.value;
if (this.state.act === 0) {
//new
let data = {
name,
isenable
};
datas.push(data);
console.log(data.isenable);
} else {
//update
let index = this.state.index;
datas[index].name = name;
datas[index].isenable = isenable;
}
this.setState({
datas: datas,
act: 0
});
this.refs.myForm.reset();
this.refs.name.focus();
};
fRemove = i => {
let datas = this.state.datas;
datas.splice(i, 1);
this.setState({
datas: datas
});
this.refs.myForm.reset();
this.refs.name.focus();
};
fEdit = i => {
let data = this.state.datas[i];
this.refs.name.value = data.name;
this.refs.isenable.value = data.isenable;
this.setState({
act: 1,
index: i
});
this.refs.name.focus();
};
render() {
let datas = this.state.datas;
return (
<div className="App">
<h2>{this.state.title}</h2>
<form ref="myForm" className="myForm">
<input
type="text"
ref="name"
placeholder="your name"
className="formField"
/>
<input
type="checkbox"
ref="isenable"
placeholder="your isenable"
className="formField"
/>
<button onClick={e => this.fSubmit(e)} className="myButton">
submit
</button>
</form>
<pre>
{datas.map((data, i) => (
<li key={i} className="myList">
{data.name} - {(data.isenable || false).toString()}
<button onClick={() => this.fRemove(i)} className="myListButton">
remove
</button>
<button onClick={() => this.fEdit(i)} className="myListButton">
edit
</button>
</li>
))}
</pre>
</div>
);
}
}
export default App;

When working with checkboxes, refer to the checked property not the value. This is the true or false state of the checkbox.
In fSubmit:
let isenable = this.refs.isenable.checked;
In fEdit:
this.refs.isenable.checked = data.isenable;
In the render:
{data.name} - {data.isenable ? 'on' : 'off'}
Working demo
Complete code with fixes:
class App extends Component {
constructor(props) {
super(props);
this.state = {
title: "React Simple CRUD Application",
act: 0,
index: "",
datas: []
};
}
componentDidMount() {
this.refs.name.focus();
}
handleChange = e => {
console.log(e.target.value);
};
fSubmit = e => {
e.preventDefault();
console.log("try");
let datas = this.state.datas;
let name = this.refs.name.value;
let isenable = this.refs.isenable.checked;
if (this.state.act === 0) {
//new
let data = {
name,
isenable
};
datas.push(data);
console.log(data.isenable);
} else {
//update
let index = this.state.index;
datas[index].name = name;
datas[index].isenable = isenable;
}
this.setState({
datas: datas,
act: 0
});
this.refs.myForm.reset();
this.refs.name.focus();
};
fRemove = i => {
let datas = this.state.datas;
datas.splice(i, 1);
this.setState({
datas: datas
});
this.refs.myForm.reset();
this.refs.name.focus();
};
fEdit = i => {
let data = this.state.datas[i];
this.refs.name.value = data.name;
this.refs.isenable.checked = data.isenable;
this.setState({
act: 1,
index: i
});
this.refs.name.focus();
};
render() {
let datas = this.state.datas;
return (
<div className="App">
<h2>{this.state.title}</h2>
<form ref="myForm" className="myForm">
<input
type="text"
ref="name"
placeholder="your name"
className="formField"
/>
<input
type="checkbox"
ref="isenable"
placeholder="your isenable"
className="formField"
/>
<button onClick={e => this.fSubmit(e)} className="myButton">
submit
</button>
</form>
<pre>
{datas.map((data, i) => (
<li key={i} className="myList">
{data.name} - {data.isenable ? 'on' : 'off'}
<button onClick={() => this.fRemove(i)} className="myListButton">
remove
</button>
<button onClick={() => this.fEdit(i)} className="myListButton">
edit
</button>
</li>
))}
</pre>
</div>
);
}
}
Sidenote: I wouldn't use Refs in this case. Take a look at the docs, you can see when to use Refs and when not to. The Forms docs cover how to handle forms without Refs.

You should use the checked attribute of the isenable element to determine whether the checkbox is checked and put this value in your form. You can check the mdn docs: https://developer.mozilla.org/fr/docs/Web/HTML/Element/Input/checkbox

Related

Set input to a controller input using button onclick method in React JS

I find myself struggling to change the form input value from the button onClick handler. My problem is escalated by the fact that I have the line items on a form and things become even more complex that way. I tried to bring in a ref to set value,,, the value is displayed but at the form state after submission it remains empty which means the value is not being set. Below are all my code files. May someone kindly help me on where I may be missing the point.
class VehicleTemplate extends React.Component {
constructor(props){
super(props);
this.ws = new WebSocket('ws://localhost:8000/ws/weightData/');
this.socketRef = null;
this.state = {
data: 0,
name: '',
model: '',
plate_number: '',
type: 'truck',
wagons: [{ index: uuid(), label: '', type: 'once', weight: '' }],
total: 0,
};
this.onSubmit = this.onSubmit.bind(this);
this.handleChange= this.handleChange.bind(this);
this.handleChangeTable = this.handleChangeTable.bind(this);
this.addNewRow = this.addNewRow.bind(this);
this.deleteRow = this.deleteRow.bind(this);
this.handleLineItemChange = this.handleLineItemChange.bind(this);
}
componentDidMount() {
this.ws.onopen = () => {
// on connecting, do nothing but log it to the console
console.log('connected')
}
this.ws.onmessage = evt => {
// listen to data sent from the websocket server
// const message = JSON.parse(evt.data)
const {data} = this.state;
this.setState({data: evt.data})
// this.setState({this.state.lines.weight: data})
}
this.ws.onclose = () => {
console.log('disconnected')
// automatically try to reconnect on connection loss
}
};
onSubmit = (e) => {
e.preventDefault();
const {
name,
model,
plate_number,
type,
wagons,
} = this.state;
const vehicle = {
name,
model,
plate_number,
type,
wagons,
};
this.props.addVehicle(vehicle, this.props.token);
console.log(vehicle);
this.setState({
name: '',
model: '',
plate_number: '',
wagons: [],
});
};
handleLineItemChange = (elementIndex) => (event) => {
let wagons = this.state.wagons.map((item, i) => {
if (elementIndex !== i) return item
return {...item, [event.target.name]: event.target.value}
})
this.setState({wagons})
}
handleChange = name => event => {
this.setState({
[name]: event.target.value,
});
};
handleChangeTable = (name, id) => event => {
this.updateItem(id, { [name]: event.target.value });
};
addNewRow = (event) => {
this.setState({
wagons: this.state.wagons.concat(
[{index: uuid(), label: '', type: 'once', weight: '' }]
)
})
}
deleteRow = (index) => (event) => {
this.setState({
wagons: this.state.wagons.filter((item, i) => {
return index !== i
})
})
}
handleReorderLineItems = (newLineItems) => {
this.setState({
wagons: newLineItems,
})
}
clickOnDelete(record) {
this.setState({
wagons: this.state.lines.filter(r => r !== record)
});
}
render() {
const { classes } = this.props;
const {
data,
name,
model,
plate_number,
wagons,
} = this.state;
return (
<InformationTechnologyLayout>
<PapperBlock title="ADD VEHICLE" icon="ios-document-outline" desc="VEHICLE">
<Form>
<div style={{ clear: 'both' }} />
<h1>WEIGHT: {data}KG</h1>
<Grid container>
<Grid item xs={6}>
<Controls.Input
name="name"
label="Name"
value={name}
onChange={this.handleChange('name')}
/>
<Controls.Input
name="model"
label="MODEL"
value={model}
onChange={this.handleChange('model')}
/>
</Grid>
<Grid item xs={6}>
<Controls.Input
name="plate_number"
label="PLATE NUMBER"
value={plate_number}
onChange={this.handleChange('plate_number')}
/>
</Grid>
</Grid>
<Extensions
items={wagons}
addHandler={this.addNewRow}
changeHandler={this.handleLineItemChange}
focusHandler={this.handleFocusSelect}
deleteHandler={this.deleteRow}
reorderHandler={this.handleReorderLineItems}
data ={data}
/>
<div className='valueTable'>
<div className='row'>
<div className='label'>Subtotal</div>
<div className='value'>{this.calcLineItemsTotal()}KG</div>
</div>
<div className='row'>
<div className='label'>Total Due</div>
<div className='value'>{this.calcGrandTotal()}KG</div>
</div>
</div>
<Button variant="contained" onClick={this.onSubmit}>SUBMIT</Button>
</Form>
</PapperBlock>
</InformationTechnologyLayout>
);
}
}
On top is the main form component which has got Vehicle exetnsions and I am getting my weight from a websocket connection streaming scale outputs.
class Extensions extends Component {
handleDragEnd = (result) => {
if (!result.destination) return
// helper function to reorder result (src: react-beautiful-dnd docs)
const reorder = (list, startIndex, endIndex) => {
const result = Array.from(list)
const [removed] = result.splice(startIndex, 1)
result.splice(endIndex, 0, removed)
return result
}
// perform reorder
const lineItems = reorder(
this.props.items,
result.source.index,
result.destination.index
)
// call parent handler with new state representation
this.props.reorderHandler(lineItems)
}
render = () => {
const {
items,
addHandler,
changeHandler,
focusHandler,
deleteHandler,
reorderHandler,
products,
data,
readOnly,
} = this.props
return (
<form>
<div className='lineItems'>
<div className='gridTable'>
<DragDropContext onDragEnd={this.handleDragEnd}>
<Droppable droppableId="droppable">
{(provided, snapshot) => (
<div
ref={provided.innerRef}
className= 'listDraggingOver'
>
{this.props.items.map((item, i) => (
<Draggable key={item.index} draggableId={item.index} index={i}>
{(provided, snapshot) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
style={provided.draggableProps.style}
className='listItemDragging'
>
<Extension
addHandler={addHandler}
changeHandler={changeHandler}
focusHandler={focusHandler}
deleteHandler={deleteHandler}
reorderHandler={reorderHandler}
data={data}
style={{color: 'red'}}
key={i + item.index}
index={i}
name={item.index}
label={item.label}
weight={item.weight}
/>
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
</div>
<div className='addItem'>
<button type="button" onClick={addHandler}><AddIcon size="1.25em" className='addIcon' /> Add Item</button>
</div>
</div>
</form>
)
}
}
This are the extensions and the last file is where I would like to capture weight from
class LineItem extends Component {
constructor(props){
super(props);
this.ref = React.createRef();
this.state = {
buttonState: false,
};
}
requestWeight = () => {
const { weight } = this.props;
const {buttonState} =this.state;
this.ref.current.value = this.props.data;
this.setState({
buttonState: true
})
};
render = () => {
const { index, label, weight } = this.props;
const {buttonState} = this.state;
return (
<div className='lineItem'>
<div>{index + 1}</div>
<Controls.Input
name="label"
label="LABEL"
value={label}
onChange={this.props.changeHandler(index)}
/>
<input
className='currency'
type='number'
readOnly={true}
ref={this.ref}
name='weight'
onChange={this.props.changeHandler(index)}
/>
<div>
<button type="button"
className='requestItems'
onClick={this.requestWeight}
disabled={buttonState}
>REQUEST WEIGHT</button>
</div>
<div>
<button type="button"
className='deleteItem'
onClick={this.props.deleteHandler(index)}
><DeleteIcon size="1.25em" /></button>
</div>
</div>
)
}
}
export default LineItem
If I add the value and put weight on the input then the ref stops working. I assume I might be missing something between my handleChange function and the requestWeight function but I really dont know what exaclty

React doesn't render form autofill suggestions

I'm using react to create a panel to add a new product. I've created a separate auto-complete class which is supposed to render an input element and a list of suggested autofill items underneath. The input element shows but not the autofill suggestions. Have a look at the code
Autofill class
import React, { Component } from "react";
import firebase from "../Firebase";
export default class AutoCompleteDistID extends Component {
constructor() {
super();
this.state = {
sellerName: [],
sellerId: [],
suggestions: [],
};
}
componentDidMount() {
var sellerRef = firebase.database().ref().child("Sellers");
sellerRef.once("value", (snapshot) => {
snapshot.forEach((childSnap) => {
var distrName = childSnap.val().sellerName;
var distrId = childSnap.val().sellerName.sellerId;
// var distrName = [{ name: data.sellerName }];
this.setState((prevState) => {
return {
sellerName: [...prevState.sellerName, distrName],
sellerId: [...prevState.sellerId, distrId],
suggestions: [...prevState.suggestions, distrName],
};
});
});
});
}
onTextChange = (e) => {
var sellerNames = [this.state.sellerName];
const value = e.target.value;
let newSuggestions = [];
if (value.length > 0) {
const regex = new RegExp(`^${value}`, "i");
newSuggestions = sellerNames.sort().filter((v) => regex.test(v));
}
this.setState(() => ({ newSuggestions }));
};
renderSuggestions() {
const newSuggestions = this.state.suggestions;
if (newSuggestions.length === 0) {
return null;
}
return (
<ul>
{newSuggestions.map((item) => (
<li>{item}</li>
))}
</ul>
);
}
render() {
return (
<div>
<input onChange={this.onTextChange} />
{this.renderSuggestions}
</div>
);
}
}
Main form
import React, { Component } from "react";
import firebase from "../Firebase";
import AutoCompleteDistID from "./AutoCompleteDistID";
export default class Products extends Component {
constructor() {
super();
this.state = {
description: "",
prodQty: "",
};
this.pushProduct = this.pushProduct.bind(this);
}
handleFormChange = (event) => {
const target = event.target;
const colName = target.name;
this.setState({
[colName]: event.target.value,
});
};
pushProduct() {
const userRef = firebase.database().ref().child("Users"); //Get reference to Users DB
const prodData = this.state;
userRef.push(prodData);
}
render() {
return (
<div>
<br />
<form style={{ border: "solid", borderWidth: "1px", width: "600px" }}>
<br />
<input
type="text"
value={this.state.prodQty}
placeholder="Available Quantity"
onChange={this.handleFormChange}
name="prodQty"
/>
<input
type="text"
value={this.state.description}
placeholder="Description"
onChange={this.handleFormChange}
name="description"
/>
<AutoCompleteDistID />
<br />
<br />
</form>
<button onClick={this.pushProduct} type="button">
Add Product
</button>
<br />
</div>
);
}
}
State variable is suggestions but you are setting newSuggestions.
onTextChange = (e) => {
var sellerNames = [this.state.sellerName];
const value = e.target.value;
let newSuggestions = [];
if (value.length > 0) {
const regex = new RegExp(`^${value}`, "i");
newSuggestions = sellerNames.sort().filter((v) => regex.test(v));
}
// HERE IS THE MISTAKE
this.setState(() => ({ suggestions: newSuggestions }));
};
In AutoCompleteDistID render method
render() {
return (
<div>
<input onChange={this.onTextChange} />
{this.renderSuggestions()}
</div>
);
}

using component state in another component react js

Im working on a little web app, and im stuck on getting the answers data from answer class that i created.
to sum the project, i have a class createQuiz, where i handle the input for question data, and i have an answerOptions state array to collect all the answers, but i created another component answer to have the states of the answers and when i modify them, the answeroptions dont update.
Here is the code for the answer class :
import React, {Component} from 'react';
import createQuiz from './CreateQuiz'
export default class Answer extends Component {
constructor(props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.onChangeAnswerValidity = this.onChangeAnswerValidity.bind(this);
this.ChangeValidityState = this.ChangeValidityState.bind(this);
this.state = {
answerText : '',
answerValidity : false
}
}
getCurrentState(){
return (this.state)
}
handleInputChange(event) {
this.setState({
answerText : event.target.value
})
}
onChangeAnswerValidity(event){
this.setState({
answerValidity : !event.target.value
})
}
ChangeValidityState(event){
this.setState({
answerValidity : !event.target.value
})
}
render() {
return (
<div>
<input type="text"
className="form-control"
value={this.state.answerText}
onChange={this.handleInputChange}
/>
<input type="radio"
className="form-control"
value={this.state.answerValidity}
checked={this.state.answerValidity}
onChange={this.onChangeAnswerValidity}
/>
</div>
)
}
}
and here is the code for the create quiz class :
import React, {Component} from 'react';
import axios from 'axios';
import Answer from './Answer';
export default class CreateQuiz extends Component {
constructor(props) {
super(props);
this.onChangeQuestion = this.onChangeQuestion.bind(this);
this.onChangeQuestionTitle = this.onChangeQuestionTitle.bind(this);
this.onChangeAnswerOptions = this.onChangeAnswerOptions.bind(this);
this.onAddItem = this.onAddItem.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.onChangeQuestionAutor = this.onChangeQuestionAutor.bind(this);
this.onChangeValue = this.onChangeValue.bind(this);
this.onChangeAnswerValidity = this.onChangeAnswerValidity.bind(this);
this.onSubmit = this.onSubmit.bind(this);
// this.GenerateAnswers = this.GenerateAnswers.bind(this);
this.state = {
questionTitle: '',
questionAutor: '',
question: '',
answers : [],
answerOptions: [],
}
}
onChangeValue = event => {
this.setState({ currentAnswerValue: event.target.value });
};
onAddItem = () => {
// not allowed AND not working
this.setState(state => {
const newAnswer = {
answerText : '',
answerValidity : false
};
const list = this.state.answerOptions.push(newAnswer);
return {
list,
};
});
};
handleInputChange(event) {
const newIds = this.state.answerOptions.slice() //copy the array
const index = this.state.answerOptions.findIndex((el) => (el.id === event.params.id))
newIds[index].answerText = event.target.value //execute the manipulations
this.setState({answerOptions: newIds}) //set the new state
}
onChangeAnswerValidity(event){
const newIds = this.state.answerOptions.slice() //copy the array
const index = this.state.answerOptions.findIndex((el) => el.answerText === event.target.value)
newIds[index].answerValidity = event.target.value //execute the manipulations
this.setState({answerOptions: newIds}) //set the new state
}
onChangeQuestionAutor(e){
this.setState({
questionAutor: e.target.value
});
}
onChangeQuestionTitle(e) {
this.setState({
questionTitle: e.target.value
});
}
onChangeQuestion(e) {
this.setState({
question: e.target.value
});
}
onChangeAnswerOptions(e) {
this.setState({
answerOptions: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
console.log(`Form submitted:`);
console.log(`questionTitle: ${this.state.questionTitle}`);
console.log(`questionAutor: ${this.state.questionAutor}`);
console.log(`question: ${this.state.question}`);
// this.GenerateAnswers();
console.log(`answerOptions: ${this.state.answers}`);
const newQuiz = {
questionTitle: this.state.questionTitle,
questionAutor: this.state.questionAutor,
question: this.state.question,
answerOptions: this.state.answers,
}
axios.post('http://localhost:4000/quizzes/add', newQuiz)
.then(res => console.log(res.data));
this.setState({
questionTitle: '',
questionAutor: '',
question: '',
answers : [],
answerOptions: []
})
}
answerList(){
return this.state.answerOptions.map(function(currentAnswer, index) {
return <Answer answer = {currentAnswer} key = {index}/>;
});
}
// GenerateAnswers(){
// const newAnswers = this.state.answers
// this.state.answerOptions.map(function(currentAnswer, index){
// const newAnswer = this.state.answerOptions[index].getCurrentState()
// newAnswers.push(newAnswer)
// });
// this.setState({answers: newAnswers});
// }
render() {
return (
<div style={{marginTop: 20}}>
<h3>Create new question</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Question Title: </label>
<input type="text"
className="form-control"
value={this.state.questionTitle}
onChange={this.onChangeQuestionTitle}
/>
</div>
<div className="form-group">
<label>Question Autor: </label>
<input type="text"
className="form-control"
value={this.state.questionAutor}
onChange={this.onChangeQuestionAutor}
/>
</div>
<div className="form-group">
<label>Question: </label>
<input type="text"
className="form-control"
value={this.state.question}
onChange={this.onChangeQuestion}
/>
</div>
<div>
<ul>
{this.answerList()}
</ul>
</div>
<div className="form-group">
<button type="button" onClick = {this.onAddItem} className="btn btn-primary"> Add answer </button>
</div>
<div className="form-group">
<input type="submit" value="submit Question" className="btn btn-primary" />
</div>
</form>
</div>
)
}
}
when i send the data to the database i always have in the answer fields empty string and false no update has been done.
thanks a lot,
Boubker ELAMRI
You’re modifying the list, so react doesn’t know it’s changed. You need to create a new array first, before setting the state
const list = Array.from(this.state.answerOptions)
list.push(newAnswer)

How to create an array based on multiple inputs

I am trying create an array with some objects in it, Im trying to gather the data from multiple inputs. I am creating a restaurant Menu, where I will have different titles such as Breakfasts, Entrees... and under each title I will have different plates.
Im trying to create an array like this:
menu: [
[ 'Lunch',
[{plate: 'Rice and Beans', description: 'Rice and Beans for Lunch', price: 50.49 }]
]
[ 'Dinner',
[{plate: 'Some Dinner', description: 'Dinner Description', price: 35.49 }]
]
]
The question is, how do I add first a Title, and under that title how do I add plates?
I also wanted to know how to make it, so I made it for practice. I hope it helps.
import React from 'react';
class MenuInput extends React.Component {
render() {
const {id, handleInput} = this.props;
return (
<div>
Title : <input name="title" onChange={(e) => handleInput(id, e)}/>
Plate : <input name="plate" onChange={(e) => handleInput(id, e)}/>
Description : <input name="description" onChange={(e) => handleInput(id, e)}/>
Price : <input name="price" onChange={(e) => handleInput(id, e)}/>
</div>
)
}
}
export default class Menu extends React.Component {
state = {
inputCount: 1,
inputData: [[]],
result: []
}
saveData = (e) => {
const {inputData, result} = this.state;
inputData.forEach(input => {
const {title, plate, description, price} = input;
const findInputIndex = result.findIndex(data => data.indexOf(title) >= 0);
if (findInputIndex >= 0) {
const [menuName, menuList] = result[findInputIndex];
result[findInputIndex] = [menuName, [...menuList, {plate, description, price}]]
} else {
result.push([title, [{plate, description, price}]])
}
});
this.setState({
result
})
}
handleInput = (id, e) => {
const {name, value} = e.target;
const {inputData} = this.state;
inputData[id] = {...inputData[id], [name]: value};
this.setState({
inputData
})
}
addInput = () => {
const {inputCount, inputData} = this.state;
this.setState({
inputCount: inputCount + 1,
inputData: [...inputData, []]
})
};
getInputList = () => {
const {inputCount} = this.state;
let inputList = [];
for (let i = 0; i < inputCount; i++) {
inputList.push(<MenuInput id={i} key={i} handleInput={this.handleInput}/>)
}
return inputList
}
render() {
const {result} = this.state;
console.log(result)
return (
<div>
{this.getInputList()}
<button onClick={this.addInput}>Add Plate</button>
<br/>
<button onClick={this.saveData}>save</button>
{
result.length > 0 && result.map(res => {
const [menuName, menuList] = res;
return (
<div key={menuName}>
<strong>Title : {menuName}</strong>
{menuList.map(menu => {
const {plate, description, price} = menu;
return(
<div key={plate}>
<span style={{marginRight : '10px'}}>plate : {plate}</span>
<span style={{marginRight : '10px'}}>description : {description}</span>
<span>price : {price}</span>
</div>
)
})}
</div>
)
})
}
</div>
)
}
}

React: search form with multiple inputs is submitting separate search each time additional input is used

My search form is dynmically created using a ajax call for the inputs. Each input can then be used alone or in combination with other inputs to narrow down the search results. The problem I am having is that the submit method is running a new search each time an additional input is added to the form. For example: User just searches with one input. Submit method runs once. User searches with two inputs. Search runs once for the single input and then another time for the two inputs. And so on...
Here is my parent file..
class SearchPage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
labels: [],
contracts: [],
formValues:[],
pdfs:[],
titles:[],
alertShow: false,
show: false,
};
this.onClick = this.handleContract.bind(this);
this.handleShow = this.handleShow.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleShowAlert = this.handleShowAlert.bind(this);
this.handleCloseAlert = this.handleCloseAlert.bind(this)
}
initialState = {
formValues: {},
}
state = this.initialState
componentDidMount(){
this.loadLabels();
}
componentWillUnmount(){
}
toggleHidden () {
this.setState({
isHidden: !this.state.isHidden
})
}
handleFormReset = () => {
this.setState(() => this.initialState)
this.setState({contracts:[]})
}
handleClose() {
this.setState({ show: false });
}
handleShow() {
this.setState({ show: true });
}
handleCloseAlert() {
this.setState({ alertShow: false });
}
handleShowAlert() {
this.setState({ alertShow: true });
}
loadLabels = () => {
API.getLabels()
.then(res => {
const labels = res.data;
this.setState({ labels })
})
.catch(err => console.log(err));
};
handleInputChange = (key, value) => {
const newFormValues = Object.assign({}, this.state.formValues, {[key]: value});
this.setState({ formValues: newFormValues })
};
handleContract = (id) => {
API.openRow(id)
.then(res => {
const pdfs = res.data;
this.setState({pdfs});
this.props.history.push({
state: { labels:this.state.labels,
pdfs:this.state.pdfs,
titles:this.state.titles }
})
})
.catch(err => console.log(err));
API.titles(id)
.then(res => {
const titles = res.data;
this.setState({titles});
})
this.setState({ show: true });
}
handleFormSubmit = event => {
event.preventDefault();
const formData = this.state.formValues
let query = '';
let keys = Object.keys(formData);
keys.map(k => {
if (query !== "")
query += `&`;
query += `filter=`
query += `${k}|${formData[k]}`
return this.loadContracts(query);
})
};
noResults() {
this.setState({alertShow:true})
}
loadContracts = (query) => {
API.search(query)
.then(res => {
const contracts = res.data;
if (contracts.length > 0 ){
this.setState({ contracts });
}
else {
this.noResults();
this.setState({contracts:[]});
};
})
.catch(err => console.log(err));
};
render() {
return (
<div className="container" style={{ marginTop: "80px" }}>
<div className="jumbotron">
<div className="container">
<h1>Contract Document Search</h1>
</div>
<br/>
<Container>
<SearchForm
labels={this.state.labels}
handleFormSubmit={this.handleFormSubmit}
handleInputChange={this.handleInputChange}
handleReset={this.handleReset}
handleFormReset={this.handleFormReset}
/>
<div className='modal'>
<Modal show={this.state.alertShow}
onHide={this.handleCloseAlert}
{...this.props}
size="sm"
aria-labelledby="contained-modal-title-vcenter"
centered>
<Modal.Header closeButton>
<Modal.Body>No results found</Modal.Body>
</Modal.Header>
</Modal>
</div>
</Container>
</div>
<div className="container">
<div className="jumbotron-fluid">
</div>
<SearchResults
labels={this.state.labels}
contracts={this.state.contracts}
pdfs={this.state.pdfs}
handleContract={this.onClick}
handleTitles={this.onClick}
/>
<br/>
<br/>
</div>
);
}
}
export default SearchPage;
And My search form component..
export default class SearchForm extends Component {
constructor(...args) {
super(...args);
this.state = {
};
}
render() {
return (
<form className="form-inline col-md-12" onReset={this.props.handleFormReset}>
{this.props.labels.map(label => (
<div className="card border-0 mx-auto" style={styles} key={label.Id}>
<ul className="list-inline ">
<span>
<li>
<Labels htmlFor={label.DisplayName} >{label.DisplayName}:</Labels>
</li>
<li >
<Input
key={label.Id}
onChange={(event) => {
this.props.handleInputChange(label.DataField, event.target.value)}}
value={this.props.newFormValues}
maxLength="999"
style={{height:34}}
name="value"
type="search"
className={"form-control mb-2 mr-sm-2"}
id={label.DataField}
/>
</li>
</span>
</ul>
</div>
))}
<div className=" col-sm-12">
<Button
style={{ float: "left", marginBottom: 10 }}
className="btn btn-success"
type="submit"
onClick={this.props.handleFormSubmit}
>
Search
</Button>
<Help />
<Button
style={{ float: "left", marginBottom: 10 }}
className="btn btn-secondary"
type="reset"
onClick={this.props.handleFormReset}
>
Reset
</Button>
</div>
</form>
);
}
}
The problem was that I had my return statement inside the input mapping.
handleFormSubmit = event => {
event.preventDefault();
const formData = this.state.formValues
let query = '';
let keys = Object.keys(formData);
keys.map(k => {
if (query !== "")
query += `&`;
query += `filter=`
query += `${k}|${formData[k]}`
**return this.loadContracts(query);**
})
};
Solved by moving the return statement outside the mapping.
handleFormSubmit = event => {
event.preventDefault();
const formData = this.state.formValues
let query = '';
let keys = Object.keys(formData);
keys.map(k => {
if (query !== "")
query += `&`;
query += `filter=`
query += `${k}|${formData[k]}`
})
**return this.loadContracts(query);**
};

Categories