Creating multiple page application using react - reactjs

I have created SPA using react and hence my address bar does not change when I move to another view.Kindly help in changing the address bar. News feed Code is
import React from 'react';
import axios from 'axios';
import Stories from './Stories';
export default class NewsFeed extends React.Component {
constructor(props) {
super(props);
this.state = { feed: [], showPopUp: false, showStoryPopUp: false, readArr: [], importantArr: [], counterArr: [], deleteArr: [] };
this.handleClose = this.handleClose.bind(this);
this.handleCreateFeed = this.handleCreateFeed.bind(this);
this.handlePost = this.handlePost.bind(this);
this.handleCreateStories = this.handleCreateStories.bind(this);
}
componentWillMount() {
let self = this;
axios.get('src/rest/feed.json')
.then(function (response) {
let counterArr = self.state.counterArr;
let readArr = self.state.readArr;
let deleteArr = self.state.deleteArr;
for (let item of response.data) {
counterArr.push(0);
readArr.push(false);
deleteArr.push(false);
}
self.setState({ feed: response.data });
})
.catch(function (error) {
console.log(error);
});
}
changeImportant(index) {
let arr = this.state.importantArr;
arr[parseInt(index)] = !arr[parseInt(index)];
this.setState({ importantArr: arr });
}
changeReadFlag(index) {
let arr = this.state.readArr;
arr[parseInt(index)] = !arr[parseInt(index)];
this.setState({ readArr: arr });
}
decrement(index) {
let arr = this.state.counterArr;
arr[parseInt(index)] = arr[parseInt(index)] - 1;
this.setState({ counterArr: arr });
}
handleDelete(index) {
let arr = this.state.deleteArr;
arr[parseInt(index)] = !arr[parseInt(index)];
this.setState({ deleteArr: arr });
}
increment(index) {
let arr = this.state.counterArr;
arr[parseInt(index)] = arr[parseInt(index)] + 1;
this.setState({ counterArr: arr });
}
handlePost(header, description,broker) {
// console.log(document.querySelector("#title-input").value,document.querySelector("#description-input").value)
let tempObj = { imgsrc: "images1.jpg" };
// tempObj.header = document.querySelector("#title-input").value;
// tempObj.description = document.querySelector("#description-input").value;
tempObj.header = header;
tempObj.description = description;
tempObj.broker = broker;
let tempArr = this.state.feed;
tempArr.push(tempObj);
let counterArr = this.state.counterArr.push(0);
this.setState({ showStoryPopUp: false });
}
handleClose() {
this.setState({ showPopUp: false, showStoryPopUp: false })
}
handleCreateFeed() {
this.setState({ showPopUp: true });
}
handleCreateStories() {
this.setState({ showStoryPopUp: true });
}
render() {
return (
<div className="email-class lis-cls">
{this.state.showStoryPopUp ? <Stories handlePost={this.handlePost} handleClose={this.handleClose} /> : null}
{this.props.userType === 'admin' ? <button id="story-btn" type="button" className="btn btn-primary fixed-cls fa fa-pencil" style={{ display: this.state.showPopUp || this.state.showStoryPopUp ? 'none' : 'inline-block' }} onClick={this.handleCreateStories} > Create Stories</button> : null}
{this.state.feed.map((feed, index) => {
return (<div key={index} id={index} className={this.state.showPopUp || this.state.showStoryPopUp ? 'row row-feed hide-cls' : this.state.deleteArr[index] ? 'row row-feed hide-cls' : 'row row-feed'} >
<h4 className="list-header">{feed.header}</h4>
<img src={"src/img/" + feed.imgsrc} alt="Smiley face" height="100" width="100" />
<span className="feed-text">{feed.description}</span>
<div className="row">
<div className="col-md-1">
<span className={this.state.readArr[index] ? "fa fa-check-circle pull-right" : ""}></span>
</div>
<div className="col-md-1">
<div className="pull-right">
<div className="fa fa-arrow-up display-block-cls" onClick={this.increment.bind(this, index)}></div>
<div className={this.state.counterArr[index] == 0 ? "vote-cls" : this.state.counterArr[index] > 0 ? "vote-cls upvote" : "vote-cls downvote"}>
{this.state.counterArr[index]}
</div>
<div className="fa fa-arrow-down display-block-cls" onClick={this.decrement.bind(this, index)}> </div>
</div>
</div>
<div className="col-md-8">
<button id="read" className="btn btn-success fa fa-pencil" onClick={this.changeReadFlag.bind(this, index)}> Read </button>
<button id="delete" className="btn btn-danger fa fa-trash-o" onClick={this.handleDelete.bind(this, index)}> Delete </button>
<button className="btn btn-primary fa fa-exclamation" onClick={this.changeImportant.bind(this, index)}> Important </button>
</div>
</div>
<hr className={this.state.importantArr[index] ? 'imp-cls' : 'hr-cls'} />
</div>)
})}
</div>
);
}
}
stoies code is
import React from 'react';
export default class Stories extends React.Component {
constructor(props) {
super(props);
this.handleClose = this.handleClose.bind(this);
this.handlePost = this.handlePost.bind(this);
}
handleClose() {
this.props.handleClose();
}
handlePost(){
let header = document.querySelector("#title-input").value;
let description = document.querySelector("#description-story-input").value;
let broker = document.querySelector("#broker-input").value;
this.props.handlePost(header,description,broker);
}
render() {
return (<div className={'popup-cls add-story-top'}>
<div className={'add-story email-class'}>
<img onClick={this.handleClose} className="cross-cls" src="src/img/cross.png" alt="Smiley face" height="35" width="35" />
<h4 className="list-header">Create Stories</h4>
<table>
<tbody>
<tr>
<td>
Title
</td>
<td>
<input type="text" id="title-input" />
</td>
</tr>
<tr>
<td>
Description </td>
<td> <textarea rows="4" cols="50" id="description-story-input"></textarea>
</td>
</tr>
<tr>
<td>
Broker </td>
<td> <input type="text" id="broker-input" />
</td>
</tr>
<tr>
<td>
Ticker </td>
<td> <input type="text" id="ticker-input" />
</td>
</tr>
<tr>
<td>
Category </td>
<td> <input type="text" id="category-input" />
</td>
</tr>
<tr>
<td>
Direction </td>
<td> <input type="number" min="-2" max="2" defaultValue="0" id="direction-input" />
</td>
</tr>
<tr>
<td>
Rating </td>
<td> <input type="number" min="-5" max="5" defaultValue="0" id="rating-input" />
</td>
</tr>
<tr>
<td>
Score </td>
<td> <input type="number" min="-4" max="4" defaultValue="0" id="score-input" />
</td>
</tr>
<tr>
<td>
Trade Price </td>
<td> <input type="text" id="trade-price-input" />
</td>
</tr>
<tr>
<td>
Pre Trade Price </td>
<td> <input type="text" id="pre-trade-input" />
</td>
</tr>
<tr>
<td>
Attachment </td>
<td> <input type="file" id="attachment-input" />
</td>
</tr>
<tr>
<td>
Links </td>
<td> <input type="text" id="links-input" />
</td>
</tr>
<tr>
<td>
Percentage Change </td>
<td> <input type="text" id="percentage-change-input" />
</td>
</tr>
<tr>
<td>
Tags </td>
<td> <input type="text" id="tag-input" />
</td>
</tr>
<tr>
<td></td>
<td><button onClick={this.handlePost} id="post-btn" type="button" className="btn btn-primary fa fa-envelope" > Post</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>);
}
}
login code is
import React from 'react';
import axios from 'axios';
export default class Login extends React.Component {
constructor(props) {
super(props);
this.state = { login: false, userName: '', password: '' ,isValid : true};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeUserName = this.handleChangeUserName.bind(this);
this.handleChangePassword = this.handleChangePassword.bind(this);
}
handleSubmit() {
let self = this;
axios.get('src/rest/login.json')
.then(function (response) {
response.data.map((user)=>{
if(user.userName === self.state.userName && user.password === self.state.password ){
self.props.setLogin( true,user.role);
self.setState({isValid :true })
}else{
self.setState({isValid :false })
}
});
})
.catch(function (error) {
console.log(error);
});
}
handleChangeUserName(event){
this.setState({userName : event.target.value});
}
handleChangePassword(event){
this.setState({password : event.target.value});
}
render() {
return (
<div className="email-class email-class-div login-cls">
<div className="row row-login header-class">
<h3 className="float-class" >Login</h3>
<img src="src/img/star.png" className="float-class img-class" alt="Smiley face" height="35" width="35" />
</div>
<div className="error-div" style={{display : !this.state.isValid?'block':'none'}}>Invalid username or password</div>
<div className="row row-login androidTextbox">
<input className="col-md-6" type="text" placeholder="User ID/Email" onChange={this.handleChangeUserName}/>
</div>
<div className="row row-login androidTextbox">
<input className="col-md-6" type="password" placeholder="Password" onChange={this.handleChangePassword} />
</div>
<div className="row row-login submit-row" onClick={this.handleSubmit}>
<div id="button" >SUBMIT</div>
</div>
</div>
);
}
}
All three have same address.

I'm not sure how you are navigating without routes unless you are showing/hiding components. You could look into implementing the hash router

Related

Fetch data between two dates in React from Django API

I am trying to filter data between two dates and display it in a table. Currently, my table shows all the data from the database but I want the user to be able to select from that date to this date, and data between the specified dates to be displayed in the table.
My code:
import React from "react";
import APIHandler from "../utils/APIHandler";
import _ from "lodash";
import moment from "moment";
import DatePicker from "react-datepicker";
import { initiateGetTransactions } from "../components/Transactions";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
class FarmerStatementComponent extends React.Component {
constructor(props) {
super(props);
console.log(props.match.params.id);
}
state = {
errorRes: false,
errorMessage: "",
btnMessage: 0,
sendData: false,
orders: [],
startDate: new Date(),
endDate: new Date(),
dataLoaded: false,
formSubmitted: false,
name: "",
id: "",
};
componentDidMount() {
this.fetchFarmerData().then(response => {
console.log(response.data);
this.setState({
orders: response.data
});
});
}
handleStartDateChange = (date) => {
this.setState({
startDate: date
});
}
handleEndDateChange = (date) => {
this.setState({
endDate: date
});
}
handleSubmit = (event) => {
debugger;
event.preventDefault();
const data = { startDate:this.state.startDate, endDate:this.state.endDate};
}
async fetchFarmerData() {
var apihandler = new APIHandler();
var farmerdata = await apihandler.fetchFarmerDetails(this.props.match.params.id);
console.log(farmerdata);
this.setState({ orders: farmerdata.data.data.orders });
this.setState({ name: farmerdata.data.data.name });
this.setState({ phone: farmerdata.data.data.phone });
this.setState({ dataLoaded: true });
}
print() {
window.print();
}
render() {
return (
<section className="content">
<div className="container-fluid">
<div className="block-header">
<h2>FARMER STATEMENT</h2>
</div>
<div className="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div className="card">
<div className="header">
<h2>
{this.state.name}'S STATEMENT
</h2>
<div className="header-dropdown m-r--5">
<h2>
{this.state.id}
</h2>
</div>
</div>
<div className="body">
<div className="table-responsive">
<div id="DataTables_Table_1_wrapper" className="dataTables_wrapper form-inline dt-bootstrap">
<div className="dt-buttons">
<a className="dt-button buttons-csv buttons-html5" tabIndex="0" aria-controls="DataTables_Table_1" href="#">
<span>
<ReactHTMLTableToExcel
className="btn btn-success"
tabIndex="0"
aria-controls="DataTables_Table_1"
table="DataTables_Table_1"
filename="FarmerStatement"
sheet="Sheet"
buttonText="Excel"
/>
</span>
</a>
<a className="dt-button buttons-print" tabIndex="0" aria-controls="DataTables_Table_1" href="#" onClick={this.print}>
<span onClick={() => this.print()}>Print</span>
</a>
<br/>
<form onSubmit={this.handleSubmit}>
<button type="submit" className="btn btn-info" >
Generate Report
</button>
</form>
</div>
<div id="DataTables_Table_1_filter" className="dataTables_filter">
<form onSubmit={this.handleSubmit}>
<label>
<i className="material-icons">date_range</i>Start Date:
<DatePicker
selected={this.state.startDate}
className="form-control datepicker"
name="Start Date: 30/07/2022"
aria-controls="DataTables_Table_1"
value={this.state.startDate}
onChange={this.handleStartDateChange}
/>
</label>
<br/>
<label>
<i className="material-icons">date_range</i>End Date:
<DatePicker
selected={this.state.endDate}
className="form-control datepicker"
name="End Date: 30/07/2022"
aria-controls="DataTables_Table_1"
value={this.state.endDate}
onChange={this.handleEndDateChange}
/>
</label>
</form>
</div>
{this.state.dataLoaded === false ? (
<div className="text-center">
<div className="preloader pl-size-xl">
<div className="spinner-layer">
<div className="circle-clipper left">
<div className="circle"></div>
</div>
<div className="circle-clipper right">
<div className="circle"></div>
</div>
</div>
</div>
</div>
) : ""}
<table className="table table-bordered table-striped table-hover dataTable js-exportable" id="DataTables_Table_1" role="grid" aria-describedby="DataTables_Table_1_info">
<thead>
<tr role="row">
<th className="sorting_asc" tabIndex="0" aria-controls="DataTables_Table_1" rowSpan="1" colSpan="1" aria-sort="ascending" aria-label="Name: activate to sort column descending" style={{width: "40px"}}>
#ORDER NO
</th>
<th className="sorting" tabIndex="0" aria-controls="DataTables_Table_1" rowSpan="1" colSpan="1" aria-label="Position: activate to sort column ascending" style={{width: "150px"}}>
CUSTOMER NAME
</th>
<th className="sorting" tabIndex="0" aria-controls="DataTables_Table_1" rowSpan="1" colSpan="1" aria-label="Office: activate to sort column ascending" style={{width: "101px"}}>
KILOS
</th>
<th className="sorting" tabIndex="0" aria-controls="DataTables_Table_1" rowSpan="1" colSpan="1" aria-label="Age: activate to sort column ascending" style={{width: "100px"}}>
PRICE PER KG
</th>
<th className="sorting" tabIndex="0" aria-controls="DataTables_Table_1" rowSpan="1" colSpan="1" aria-label="Start date: activate to sort column ascending" style={{width: "115px"}}>
ORDERED ON
</th>
</tr>
</thead>
<tbody>
{this.state.orders.map((farmer) => (
<tr role="row" className="odd" key={farmer.id}>
<td className="sorting_1">{farmer.id}</td>
<td className="sorting_1">{farmer.customer.name}</td>
<td className="sorting_1">{farmer.kgs}</td>
<td className="sorting_1">{farmer.price}</td>
<td className="sorting_1">{new Date(farmer.added_on).toLocaleString()}</td>
</tr>
))}
</tbody>
</table>
<div className="dataTables_info" id="DataTables_Table_1_info" role="status" aria-live="polite">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
);
}
}
export default FarmerStatementComponent;
You can add filter in query or you can do filter to incoming data from database before passing to table

React UI doesn't get updated, why?

I have a component, called Bucket, each bucket can have multiple challenges, it looks like this,
The code I have is like this, (much-simplified version)
class CLL_Bucket extends Component {
constructor(props) {
super(props);
this.state = {};
this.state = {
…
bucketChallengesIdx: 0, // to track the index of challegnes
bucketChallenges: this.props.bucket.bucketChallenges || [],
…
};
…
this.onBucketChallengeAdd = this.onBucketChallengeAdd.bind(this);
this.onBucketChallengeIDChanged = this.onBucketChallengeIDChanged.bind(this);
this.onBucketChallengeWeightChanged = this.onBucketChallengeWeightChanged.bind(this);
}
render() {
const bucketIdx = this.props.idx;
return (
<div style={styles.container}>
<div key={bucketIdx} className="row" style={styles.bucketStyle}>
<div className="col-md-2">
…
</div>
<div key={bucketIdx} className="col-md-4">
<div>
<label>
<span className="text-center">Challenges<span>
</label>
<button type="button" className="btn btn-success btn-sm" onClick={() => this.onBucketChallengeAdd()}>Add Challenge</button>
</div>
<table className="table table-bordered table-striped show">
<thead>
<tr>
<th>Challenge ID</th>
<th>Weight</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.state.bucketChallenges.map(this.renderBucketChallenges.bind(this))}
</tbody>
</table>
</div>
…
</div>
</div>
);
}
renderBucketChallenges(bucketIdx, idx){
return (
<tr key={idx}>
<td className="col-xs-3 input-group-sm">
<Select
options={challengeIDOptions}
defaultValue={challengeIDOptions[0]}
onChange={this.onBucketChallengeIDChanged.bind(this, idx)}
value={this.state.bucketChallengesID}
isSearchable={true}
/>
</td>
<td className="col-xs-1 input-group-sm">
<input type="text" className="form-control" value={this.state.bucketChallengesWeight}
onChange={(e) => this.onBucketChallengeWeightChanged(idx, e)} disabled={this.props.readOnly}>
</input>
</td>
<td className="col-xs-1 input-group-sm">
…
</td>
<td className="col-xs-1 input-group-sm">
<input className="btn btn-danger btn-sm" id="deleteButton" type="button" value="Delete" onClick={() => this.onDeleteChallenge.bind(this, bucketIdx, idx)} />
</td>
</tr>
);
}
onBucketChallengeAdd(){
var newChallengeIndex = this.state.bucketChallengesIdx + 1;
console.log("onBucketChallengeAdd(): " + newChallengeIndex);
this.setState({bucketChallengesIdx: newChallengeIndex});
this.props.onAddChallenge(this.props.idx, newChallengeIndex);
}
The problem I’m having is, when I click the “Add Challenge” button, I can see from the React developer tool that a new challenge is being added, even though the UI is not updated. When I go to a different tab of my app and come back, the UI is added (a new row for the added challenge is there). Why? Any suggestion on how to fix this? Thanks!
The bigger question is, am I on the right track to make this happen? or i should extract challenge portion to a different component?

error: cannot read <a> property of 'undefined' but the 'undefined' object appears to be valid in another code segment

I have a state 'raterNameList', which is an array of objects with different properties (rater1name, rater1score, rater2name, rater2score, ...)
when I called this.state.raterNameList[0].rater1name, I got the error "TypeError: Cannot read property 'rater1name' of undefined", and if I put in the condition check for this.state.raterNameList[0]!=null, it appears that raterNameList[0] is null.
However, within the next code section, I called this.state.raterNameList.map and display rater1score for every item in the list, it can display the value for item #0 just fine.
I am very new to react and don't know what I did wrong.
import React, { Component } from 'react'
import '../App.css'
class Consensus extends Component {
constructor() {
super();
this.state = {
justLoaded:true,
panelval: '',
hr:'',
raterNameList: [],
r1: '',
r2:'',
r3:'',
};
this.handleChange = this.handleChange.bind(this);
this.handleChangeHR = this.handleChangeHR.bind(this);
this.handleChangeFinalScore = this.handleChangeFinalScore.bind(this);
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
getRaterList = () => {
var fetchquery="./api/consensustable?panelName=" + this.state.panelval
console.log ("Hello" + fetchquery)
console.log ("mounted =" + this.state.justLoaded)
fetch(fetchquery)
.then(res => res.json())
.then (raterNameList =>{
this.setState({raterNameList})
})
};
getRaterName =()=>{
if (this.state.raterNameList[0]!=null){
this.setState({r1: this.state.raterNameList[0].rater1name});
this.setState({r2: this.state.raterNameList[0].rater2name});
this.setState({r3: this.state.raterNameList[0].rater3name});
}
else{
this.setState({r1: "Rater1"});
this.setState({r2: "Rater2"});
this.setState({r3: "Rater3"});
}
}
handleChange(event) {
this.setState({panelval: event.target.value});
}
handleChangeHR(event) {
this.setState({hr: event.target.value});
}
handleChangeFinalScore(event) {
this.setState({finalScore: event.target.value});
}
handleClick(event) {
console.log('A name was submitted: ' + this.state.panelval);
this.setState({justLoaded: false});
event.preventDefault();
this.getRaterList();
this.getRaterName();
}
handleSubmit(event) {
event.preventDefault();
}
render () {
if (!this.state.justLoaded)
{
return( <form onSubmit={this.handleSubmit}>
<label> Consensus Panel Name: {this.state.panelval} </label>
<table>
<tbody >
<tr>
<table>
<tbody>
<td className="matchsizing">Applicant Name</td>
<td className="scorebox">{this.state.r1}</td>
<td className="scorebox">{this.state.r2}</td>
<td className="scorebox">{this.state.r3}</td>
<td className="finalscorebox">Final Score</td>
<td className="finalscorebox">Advance?</td>
</tbody>
</table>
</tr>
<tr>
<table >
{this.state.raterNameList.map((ra, i)=>(
<tbody>
<tr>
<td className="matchsizing" >{i}: {ra.applicantname} </td>
<td className="scorebox" >{ra.rater1score}</td>
<td className="scorebox" >{ra.rater2score}</td>
<td className="scorebox">{ra.rater3score}</td>
<td className="scorebox">
<input type="text" name="finalScore" value={ra.finalscore} />
</td>
<td className="scorebox">ra.advance</td>
</tr>
<tr>
<td colspan="6">
<textarea rows ="5" cols="136" className="textarea" placeholder="Enter details here..."></textarea>
</td>
</tr>
</tbody>
)
)
}
</table>
</tr>
<tr>
<td colspan="9">
<label>Human Resources Representative: </label>
<input type="text" value={this.state.hr} onChange={this.handleChangeHR} />
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Save" />
</form>
)
}
else
{
return(
<form onSubmit={this.handleSubmit}>
<label>Panel Name: </label>
<input type="text" value={this.state.panelval} onChange={this.handleChange} />
<button type="button" value="get Panel" onClick={this.handleClick}> get Panel </button>
</form>
)
}
}}
export default Consensus;
This may work for you:
import React, { Component } from "react";
import "../App.css";
class Consensus extends Component {
constructor() {
super();
this.state = {
justLoaded: true,
panelval: "",
hr: "",
raterNameList: [],
r1: "",
r2: "",
r3: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleChangeHR = this.handleChangeHR.bind(this);
this.handleChangeFinalScore = this.handleChangeFinalScore.bind(this);
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
getRaterList = cb => {
var fetchquery = "./api/consensustable?panelName=" + this.state.panelval;
console.log("Hello" + fetchquery);
console.log("mounted =" + this.state.justLoaded);
fetch(fetchquery)
.then(res => res.json())
.then(raterNameList => {
this.setState({ raterNameList });
cb(raterNameList);
});
};
getRaterName = raterNameList => {
if (raterNameList && raterNameList.length) {
this.setState({
r1: raterNameList[0].rater1name,
r2: raterNameList[0].rater2name,
r3: raterNameList[0].rater3name
});
} else {
this.setState({ r1: "Rater1", r2: "Rater2", r3: "Rater3" });
}
};
handleChange(event) {
this.setState({ panelval: event.target.value });
}
handleChangeHR(event) {
this.setState({ hr: event.target.value });
}
handleChangeFinalScore(event) {
this.setState({ finalScore: event.target.value });
}
handleClick(event) {
event.preventDefault();
console.log("A name was submitted: " + this.state.panelval);
this.setState({ justLoaded: false });
this.getRaterList(raterNameList => {
this.getRaterName(raterNameList);
});
}
handleSubmit(event) {
event.preventDefault();
}
render() {
if (!this.state.justLoaded) {
return (
<form onSubmit={this.handleSubmit}>
<label> Consensus Panel Name: {this.state.panelval} </label>
<table>
<tbody>
<tr>
<table>
<tbody>
<td className="matchsizing">Applicant Name</td>
<td className="scorebox">{this.state.r1}</td>
<td className="scorebox">{this.state.r2}</td>
<td className="scorebox">{this.state.r3}</td>
<td className="finalscorebox">Final Score</td>
<td className="finalscorebox">Advance?</td>
</tbody>
</table>
</tr>
<tr>
<table>
{this.state.raterNameList.map((ra, i) => (
<tbody>
<tr>
<td className="matchsizing">
{i}: {ra.applicantname}{" "}
</td>
<td className="scorebox">{ra.rater1score}</td>
<td className="scorebox">{ra.rater2score}</td>
<td className="scorebox">{ra.rater3score}</td>
<td className="scorebox">
<input
type="text"
name="finalScore"
value={ra.finalscore}
/>
</td>
<td className="scorebox">ra.advance</td>
</tr>
<tr>
<td colspan="6">
<textarea
rows="5"
cols="136"
className="textarea"
placeholder="Enter details here..."
/>
</td>
</tr>
</tbody>
))}
</table>
</tr>
<tr>
<td colspan="9">
<label>Human Resources Representative: </label>
<input
type="text"
value={this.state.hr}
onChange={this.handleChangeHR}
/>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Save" />
</form>
);
} else {
return (
<form onSubmit={this.handleSubmit}>
<label>Panel Name: </label>
<input
type="text"
value={this.state.panelval}
onChange={this.handleChange}
/>
<button type="button" value="get Panel" onClick={this.handleClick}>
{" "}
get Panel{" "}
</button>
</form>
);
}
}
}
export default Consensus;
handleClick(event) {
event.preventDefault();
console.log("A name was submitted: " + this.state.panelval);
this.setState({ justLoaded: false });
this.getRaterList() // <- here we made async call
this.getRaterName() // <- this function will called before we get back data
}
Explanation
You were making async call and before that response comes back you started reading state and that is not yet updated because you api call is in progress state.
What i did is added one callback function and once app call is done we will set state and call callback function so that getRaterName state will be called once we got the data.
also i've just refined
getRaterName we don't need to call setState function for each object we can update state in one shot.
you can refine other setState same way.
Also instead of setting raterName after setting raterNameList you can do this as well
getRaterList = () => {
var fetchquery="./api/consensustable?panelName=" + this.state.panelval
console.log ("Hello" + fetchquery)
console.log ("mounted =" + this.state.justLoaded)
fetch(fetchquery)
.then(res => res.json())
.then (raterNameList =>{
this.setState({
raterNameList,
r1: raterNameList[0] ? raterNameList[0].rater1name: "Rater1",
r2: raterNameList[0] ? raterNameList[0].rater2name: "Rater2",
r3: raterNameList[0] ? raterNameList[0].rater3name: "Rater3"
})
})
};
handleClick(event) {
event.preventDefault();
console.log("A name was submitted: " + this.state.panelval);
this.setState({ justLoaded: false });
this.getRaterList();
}

Add row to existing table dynamically in ReactJS

I am learning ReactJS.
I have pre-existing table rendered which contains thead and only 1 row by default. Now on button click, I want to append a row everytime the button click, but the max rows appended should not be greater than 4.
Here is my code:
import React, { Component } from "react";
import Sidebar from "../Home/Sidebar";
import axios from "axios";
import $ from "jquery";
import { isDivisibleBy100 } from "../utils/utility";
import { Chart } from "react-charts";
class Strategy extends Component {
state = {
Price: [],
chart_data: [],
loadData: true,
unit: parseFloat(0),
loadUnit: true,
};
componentDidMount() {
this.getPriceList();
}
getPriceList() {
axios.get("http://localhost:8000/listprice/").then(res => {
if (res.data.result === 1) {
this.setState({ Price: res.data.data });
}
});
}
appendRow(event) {
var rel = event.target.getAttribute("rel");
rel = parseInt(rel) + 1;
console.log(rel);
var addRow = (
<tr>
<td>
<input type="text" id={`select-type` + rel} />
</td>
<td>
<input type="text" id={`select-position` + rel} />
</td>
</tr>
);
$(".table tbody").append(appRow);
}
render() {
return (
<div className="container container_padding">
<div className="row">
<Sidebar />
<div className="col-md-9 col-sm-9 col-xs-12 white-box">
<div className="col-sm-12">
<h3 className="col-sm-4" style={{ padding: "0px" }}>
Strategy Plan:
</h3>
<div className="col-sm-7" />
<div className="col-sm-1" style={{ marginTop: "15px" }}>
<button
rel="1"
type="button"
id="addbtn"
className="btn btn-circle"
onClick={this.appendRow}
>
<i className="fa fa-plus" />
</button>
</div>
</div>
<div className="col-sm-12 a">
<div className="table-responsive">
<table className="table table-bordered">
<thead>
<tr>
<td>#</td>
<td>Type</td>
<td>Position</td>
<td>Price</td>
<td>Number</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<select
className="form-control"
name="select-type"
id="select-type"
>
<option value="select">Select</option>
<option value="one">1</option>
<option value="two">2</option>
</select>
</td>
<td>
<select
className="form-control"
name="select-position"
id="select-position"
>
<option value="select">Select</option>
<option value="a">A</option>
<option value="b">B</option>
</select>
</td>
<td>
<select
className="form-control"
name="price-list"
id="price-list"
onChange={event =>
this.handlePriceChange(event)
}
>
<option value="select">Select</option>
{this.state.Price.map(p => (
<option
value={p.pprice}
key={p.price}
>
{p.price}
</option>
))}
</select>
</td>
<td style={{ width: "180px" }}>
<input
id="input-number"
type="text"
className="form-control"
defaultValue="1"
/>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div className="col-sm-12">
<button
className="btn"
onClick={() => this.handleClick()}
>
Calculate
</button>
</div>
{this.state.loadData ? (
""
) : (
<div
style={{
width: "600px",
height: "300px",
marginTop: "35px",
marginLeft: "25px",
marginBottom: "10px"
}}
>
<Chart
data={this.state.chart_data}
series={{ type: "line" }}
axes={[
{ primary: true, type: "linear", position: "bottom" },
{ type: "linear", position: "left" }
]}
primaryCursor
secondaryCursor
tooltip
/>
</div>
)}
</div>
</div>
</div>
);
}
}
export default Strategy;
The appendRow function is not appending the row.
What am I missing? Is there any better way to achieve this?
Please suggest.
Thanks in advance
You are using jquery and directly handling real DOM. With React we use Virtual DOM and don't manipulate the real DOM. Unlike Jquery, in react you don't have to worry about handling UI. Your concern should be handling the data properly, leave the UI updates to React. You haven't provided the Table Component information here. So, I would give you a code sample which does exactly what you want to achieve. For the button you can place it where it's needed within this component.
import React from "react";
class Table extends React.Component {
state = {
data: []
};
appendChild = () => {
let { data } = this.state;
data.push(data.length); // data.length is one more than actual length since array starts from 0.
// Every time you call append row it adds new element to this array.
// You can also add objects here and use that to create row if you want.
this.setState({data});
};
render() {
return (
<table>
<thead>
<th>Type</th>
<th>Position</th>
</thead>
<tbody>
{this.state.data.map(id => (
<Row id = {id} />
))}
</tbody>
</table>
);
}
}
const Row = ({ id }) => (
<tr>
<td>
<input type="text" id={`select-type-${id}`} />
</td>
<td>
<input type="text" id={`select-position-${id}`} />
</td>
</tr>
);
Constructor method:
constructor(props) {
super(props)
this.state = {rows: []};
}
Inside your appendRow method, instead of adding the tr directly to your tbody, add the tr to the rows state:
appendRow(event) {
var rel = event.target.getAttribute("rel");
rel = parseInt(rel) + 1;
var joined = this.state.rows.concat(
<tr>
<td>
<input type="text" id={`select-type` + rel} />
</td>
<td>
<input type="text" id={`select-position` + rel} />
</td>
</tr>
);
this.setState({ rows: joined })
}
Inside your render method, just put the array in. It will be re-rendered whenever setState is called:
render() {
...
return (
...
<button
rel="1"
type="button"
id="addbtn"
className="btn btn-circle"
onClick={this.appendRow}>
<i className="fa fa-plus" />
</button>
...
<tbody>
{this.state.rows}
</tbody>
...
)
...
}

how to pass search value from one component to another [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
hello veryone im trying to make a simple search bar to search my firebase database based on the search bar queires. im trying to get the input value from 1 component and then in component 2 display the results based on the input value from component 1 using firebase queries. Can someone tell me what im doing wrong ? thanks
1 component
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { updateFilter } from '../../actions/filtered';
import { CarsRef, timeRef } from '../admin/reference';
import Searchresults from './searchresult';
class TopSearchBar extends Component {
state = {
make: '',
body: '',
priceRange: ''
}
handleSubmit = (e) => {
e.preventDefault();
this.props.updateFilter(this.state);
this.props.history.push('/cars2')
}
render(){
let content = null;
if (content !==null ) {
<Searchresults make={this.state.make} />
}
else {
<p> h </p>
}
let searchMake = ["Audi","Honda","Lamborghini","Maserati", "Subaru","Toyota"];
let cars = {
Audi: [ {body: "Sedan"}, {body: "Coupe"}, {body: "SUV"} ],
Honda: [ {body: "Sedan"}, {body: "Van"}, {body: "SUV"} ],
Lamborghini: [ {body: "Coupe"} ],
Maserati: [ {body: "Coupe"}, {body: "SUV"} ],
Mercedes: [ {body: "Convertible"}, {body: "Coupe"} ],
Subaru: [ {body: "Hatchback"} ],
Toyota: [ {body: "SUV"}, {body: "Sedan"}, {body: "Truck"} ]
}
let makes = searchMake.map((make, i) => {
return (
<option key={i} value={make}>
{make}
</option>
)
})
if(this.state.make) {
var body = cars[this.state.make].map((make, i) => {
return (
<option key={i} value={make.body}>
{make.body}
</option>)
})
}
return(
<div className="top-search-bar">
<div className="container text-align">
<form onSubmit={this.handleSubmit}>
<div className="row">
<div className="col-3">
<select className="form-control"
value={this.state.make}
onChange={(e)=>this.setState({make: e.target.value})}
>
<option value="" disabled selected>Make</option>
{makes}
</select>
</div>
<div className="col-3">
<select className="form-control"
value={this.state.body}
onChange={(e)=>this.setState({body: e.target.value})}
>
<option value="" disabled selected>Body Type</option>
{ makes ? body : null }
</select>
</div>
<div className="col-3">
<select className="form-control"
value={this.state.priceRange}
onChange={(e)=>this.setState({priceRange: e.target.value})}
>
<option value="" disabled selected>Price</option>
<option value="lowHigh">Low To High</option>
<option value="highLow">High To Low</option>
</select>
</div>
<div className="col-3">
<button type="submit" className="btn btn-success btn-block" onClick={this.handleSubmit}>Search</button>
</div>
</div>
{content}
</form>
</div>
</div>
);
}
}
2nd component
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Car from './car';
import { CarsRef, timeRef } from '../admin/reference';
import { CardImg, Button, Row, Col, Table } from 'reactstrap';
import { getsinglecar } from '../../actions/cars';
import Icon from 'react-icons-kit';
import { bin } from 'react-icons-kit/icomoon';
import { getCarsThunk } from '../../actions/cars';
import { Link } from 'react-router-dom';
class Searchresults extends Component {
// ...
state = {
Cars: [],
Carsloading: true
};
handleDelete = (id) => {
this.props.deleteCar(id);
}
componentWillMount() {
alert(`${this.props.make}`); // returns undefined
CarsRef.orderByChild(`${this.props.make}`).startAt(`${this.props.make}`).endAt(`${this.props.make}`).on('value', (snap) => {
let Cars = []
snap.forEach((child) => {
Cars.push({ ...child.val(), key: child.key });
});
console.log(Cars);
this.setState({ Cars: Cars, CarsLoading: false });
});
}
render() {
const { Cars, CarsLoading } = this.state;
const orderedcars = Cars;
let carList;
if (CarsLoading) {
carList = <div className="TaskList-empty">Loading...</div>;
} else {
carList = (
<ul className="TaskList">
{Cars.map(car => (
<div>
<Row>
<Col md="12">
<div className="card border-secondary mb-3">
<div className="card-header text-success">
<h4>
<Link to={`/cars/${car.id}`}>
</Link>
</h4>
</div>
<div className="card-body">
<Row>
<Col md="5">
<CardImg
className="carlist-margin"
top
width="100%"
src={car.link}
alt={car.make}
/>
</Col>
<Col md="4">
<Table className="striped">
<tbody>
<tr>
<td>Engine:</td>
<td>{car.engine}</td>
</tr>
<tr>
<td>Drive Type:</td>
<td>{car.drive_type}</td>
</tr>
<tr>
<td>Body:</td>
<td>{car.body_type}</td>
</tr>
<tr>
<td>Exterior Color:</td>
<td>{car.ext_color}</td>
</tr>
<tr>
<td>Interior Color:</td>
<td>{car.int_color}</td>
</tr>
<tr>
<td>Transmission:</td>
<td>{car.transmission}</td>
</tr>
<tr>
<td>VIN:</td>
<td>{car.vin}</td>
</tr>
</tbody>
</Table>
</Col>
<Col md="3">
<Table className="striped">
<tbody>
<tr>
<td className="text-primary text-right">
<strong>MSRP:</strong>
</td>
<td className="text-primary text-right">
<strong>${car.price}</strong>
</td>
</tr>
<tr>
<td className="text-danger text-right">
Dealer Discount:
</td>
<td className="text-danger text-right">
{car.sale}%
</td>
</tr>
<tr>
<td className="text-primary text-right">
<strong>Total:</strong>
</td>
<td className="text-primary text-right">
<strong>
${car.price - (car.price * car.sale) / 100}
</strong>
</td>
</tr>
<tr>
<td className="text-primary text-right">
Est. Lease:
</td>
<td className="text-primary text-right">
$230/m*
</td>
</tr>
<tr>
<td className="text-primary text-right">
Est. Finance:
</td>
<td className="text-primary text-right">
$330/m*
</td>
</tr>
<tr>
<td className="text-right" />
<td className="text-right">
<Link to={`/cars/${car.id}`}>
<Button className="btn btn-success">
More
</Button>
</Link>
</td>
</tr>
</tbody>
</Table>
</Col>
</Row>
</div>
</div>
</Col>
</Row>
</div>
))}
</ul>
);
}
return carList;
}
}
export default Searchresults
;
You have to connect your 2nd component to the Redux Store and create a MapStateToProps to have access to the properties you need.
First create the MapStateToProps
const mapStateToProps = state => {
return {
make: state.make// place here the name of the property in your reducer
}
}
Then connect it to the Redux Store.
export default connect(mapStateToProps)(Searchresults)
From now on you will have access the prop "make" (or whatever name you give in on your MapStateToProps).
Take a look at this example from Redux Documentation
If you show me your actions, I may be more specific in my response.

Resources