Cannot mix a URL string with props in ReactJS - reactjs

i am new on ReactJS and i am trying to find the correct way to mix a props of a parent component with a normal string URL
in my Child component i have two props in my child component:
this.props.originalUrl = https://server.com
this.props.todayDate = "2018-08-16"
and i have a url lets say it is
let url = https://server.com/123/2018-08-16/blabla
what i want is to make it dynamic url like
let url = `${this.props.originalUrl }/123/${this.props.todayDate }/blabla`
But when i use
let url = `${this.props.originalUrl }/123/2018-08-16/blabla`
The console give me the correct URL that i want
https://server.com/123/2018-08-16/blabla
but with two props like this
let url = `${this.props.originalUrl }/123/${this.props.todayDate}/blabla`
the console give me
https://server.com/123//blabla without the date
How can i mix them currently ??
Note: when i use {this.props.todayDate} in the Child componenet return it is look work and rendered as 2018-08-16
this is the full code
import React, { Component } from 'react';
import { extend } from 'underscore';
import { translate, Trans} from 'react-i18next';
import axios from 'axios';
import { Alert } from 'react-alert'
import TableNav from './tableNav';
import Table from './table';
class TableContainer extends Component {
constructor(props) {
super(props);
this.state = {
sortBy: 'id',
filteredData: [],
checkedboxArray: [],
sortingOptions: [
'id'],
sortingDirection: {
'id': true,
},
data: [],
itemsPerPage: 20,
totalPages: '',
firstUrl: '',
previousUrl: '',
currentUrl: '',
nextUrl: '',
lastUrl: '',
totalItems:'',
currentPageNumber: '',
originalurl: `${this.props.cmsUrl}performances?eq(flyers.id,empty())&gte(startDateTime,${this.props.todayDate})&sort(+startDateTime)`,
performancesSelected: [],
myItemsState: true
};
let url = this.state.originalurl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages:response.data.pagination.pages,
totalItems:response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl:response.data.pagination.links.first,
previousUrl:response.data.pagination.links.previous,
currentUrl:response.data.pagination.links.current,
nextUrl:response.data.pagination.links.next,
lastUrl:response.data.pagination.links.last,
data:response.data.results,
});
});
this.getTotal = this.getTotal.bind(this);
this.onSelectChange = this.onSelectChange.bind(this);
this.onColumnClick = this.onColumnClick.bind(this);
this.filterData = this.filterData.bind(this);
this.sortData = this.sortData.bind(this);
this.checkedbox = this.checkedbox.bind(this);
this.nextPageFunc = this.nextPageFunc.bind(this);
this.previousPageFunc = this.previousPageFunc.bind(this);
this.firstpageFunc = this.firstpageFunc.bind(this);
this.lastpageFunc = this.lastpageFunc.bind(this);
}
getTotal() {
return this.state.data.length;
}
onSelectChange(e, option) {
if (option === 'sortBy') {
this.setState({ sortBy: e.target.value });
this.sortData(e.target.value, this.state.sortBy);
this.setState({ currentPage: 1});
} else {
this.setState({ itemsPerPage: e.target.value });
this.setState({ currentPage: 1});
}
}
onColumnClick(e) {
var clicked = e.target.getAttribute('class');
this.setState({ sortBy: clicked });
this.sortData(clicked, this.state.sortBy);
}
filterData() {
return this.state.data;
}
sortData(sortBy, previousSortBy) {
sortBy = sortBy.toLowerCase().replace(' ', '');
previousSortBy = previousSortBy.toLowerCase().replace(' ', '');
var ascending = this.state.sortingDirection[sortBy];
if (sortBy === previousSortBy) {
ascending = !ascending;
this.setState({ sortingDirection: extend(this.state.sortingDirection, { [sortBy]: ascending }) });
}
var data = this.state.data.sort(function(a, b) {
if(a[sortBy] < b[sortBy]) {
return ascending ? -1 : 1;
}
if(a[sortBy] > b[sortBy]) {
return ascending ? 1 : -1;
}
return 0;
});
this.setState({ data })
}
checkedbox(id){
let checkedboxArray = this.state.checkedboxArray;
let flyersAraay = this.state.data;
let performancesSelected = this.state.performancesSelected;
// if Selected ID are not in the checkedboxArray
if ( checkedboxArray.indexOf(id) === -1 ) {
checkedboxArray.push(id) ;
this.setState({checkedboxArray: checkedboxArray })
let selecObject = flyersAraay.find(function (xxx) { return xxx.id === id; });
performancesSelected.push(selecObject)
let data = JSON.stringify(performancesSelected)
sessionStorage.setItem( "Performances" , data)
}
// if Selected ID are in the checkedboxArray
else if ( checkedboxArray.indexOf(id) !== -1 ) {
let i = checkedboxArray.indexOf(id);
if (i !== -1) {
checkedboxArray.splice(i, 1);
performancesSelected.splice(i, 1);
this.setState({checkedboxArray: checkedboxArray })
let data = JSON.stringify(performancesSelected)
sessionStorage.setItem( "Performances" , data)
}
}
}
nextPageFunc() {
let StrUrl = JSON.stringify(this.state.nextUrl);
let smallUrl = StrUrl.split("external/").pop();
let editeUrl = this.props.cmsUrl + smallUrl;
let url = editeUrl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages: response.data.pagination.pages,
totalItems: response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl: response.data.pagination.links.first,
previousUrl: response.data.pagination.links.previous,
currentUrl: response.data.pagination.links.current,
nextUrl: response.data.pagination.links.next,
lastUrl: response.data.pagination.links.last,
data: response.data.results,
});
});
}
previousPageFunc() {
let StrUrl = JSON.stringify(this.state.previousUrl);
let restUrl = StrUrl.split("external/").pop();
let editeUrl = this.props.cmsUrl + restUrl;
let url = editeUrl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages: response.data.pagination.pages,
totalItems: response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl: response.data.pagination.links.first,
previousUrl: response.data.pagination.links.previous,
currentUrl: response.data.pagination.links.current,
nextUrl: response.data.pagination.links.next,
lastUrl: response.data.pagination.links.last,
data: response.data.results,
});
});
}
firstpageFunc() {
let StrUrl = JSON.stringify(this.state.firstUrl);
let restUrl = StrUrl.split("external/").pop();
let editeUrl = this.props.cmsUrl + restUrl;
let url = editeUrl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages: response.data.pagination.pages,
totalItems: response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl: response.data.pagination.links.first,
previousUrl: response.data.pagination.links.previous,
currentUrl: response.data.pagination.links.current,
nextUrl: response.data.pagination.links.next,
lastUrl: response.data.pagination.links.last,
data: response.data.results,
});
});
}
lastpageFunc() {
let StrUrl = JSON.stringify(this.state.lastUrl);
let smallUrl = StrUrl.split("external/").pop();
let editeUrl = this.props.cmsUrl + smallUrl;
let url = editeUrl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages: response.data.pagination.pages,
totalItems: response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl: response.data.pagination.links.first,
previousUrl: response.data.pagination.links.previous,
currentUrl: response.data.pagination.links.current,
nextUrl: response.data.pagination.links.next,
lastUrl: response.data.pagination.links.last,
data: response.data.results,
});
});
}
myItemsCheckbox(e) {
let state = this.state.myItemsState
if ( state === false ) {
axios.get( `${this.props.cmsUrl}performances?eq(flyers.id,empty())&gte(startDateTime,2018-08-16)&sort(+startDateTime)`, { withCredentials: true })
.then((response) => {
this.setState({
totalPages:response.data.pagination.pages,
totalItems:response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl:response.data.pagination.links.first,
previousUrl:response.data.pagination.links.previous,
currentUrl:response.data.pagination.links.current,
nextUrl:response.data.pagination.links.next,
lastUrl:response.data.pagination.links.last,
data:response.data.results,
});
});
this.setState({ myItemsState: true})
}
else if ( state === true ) {
axios.get( this.props.cmsUrl+"performances", { withCredentials: true })
.then((response) => {
this.setState({
totalPages:response.data.pagination.pages,
totalItems:response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl:response.data.pagination.links.first,
previousUrl:response.data.pagination.links.previous,
currentUrl:response.data.pagination.links.current,
nextUrl:response.data.pagination.links.next,
lastUrl:response.data.pagination.links.last,
data:response.data.results,
});
});
this.setState({ myItemsState: false })
}
}
render() {
const { itemsPerPage, totalPages, data, currentPageNumber, totalItems, firstUrl, previousUrl, currentUrl, nextUrl, lastUrl, checkedboxArray } = this.state;
return (
<div>
<div className="myItemsButton">
<Alert>{ alert => (
<span className="btn myItemsSpan ">
<input
className="inputSelect"
defaultChecked={this.state.myItemsState}
onChange={ () => { { alert.show('You have changed the Items order' )} ; this.myItemsCheckbox() } }
type="checkbox"
id="xd"
name="cc"
/>
<label htmlFor="xd"><span></span></label>
myItems
</span>
)}
</Alert>
</div>
<TableNav
itemsPerPage={itemsPerPage}
totalPages={totalPages}
data={data}
currentPageNumber={currentPageNumber}
totalItems={totalItems}
firstpageFunc={this.firstpageFunc}
previousPageFunc={this.previousPageFunc}
nextPageFunc={this.nextPageFunc}
lastpageFunc={this.lastpageFunc}
firstUrl={firstUrl}
previousUrl={previousUrl}
currentUrl={currentUrl}
nextUrl={nextUrl}
lastUrl={lastUrl} />
<Table
onColumnClick={this.onColumnClick}
checkedbox={this.checkedbox}
data={data}
checkedboxArray={checkedboxArray}
filteredData={this.filterData()} />
{ this.state.data.length === 0 && (
<table className="table noResultsTable bordered table-hover table-dark">
<tbody>
<tr>
<td>
<div className="col-12 text-center noResults">
{/* <i className="fas fa-cog"></i> */}
<i className="fa fa-exclamation-triangle"></i>
<span className="resultsText"><Trans>No results found</Trans> {this.props.todayDate} ...</span>
</div>
</td>
</tr>
</tbody>
</table>
)}
</div>
);
}
}
export default translate('translations')(TableContainer);
in the last <span className="resultsText">i can read the time as

Related

Access to api response data

My code pass in a search term and the promise api call returns one record and the data format is as below:
` json api data
0:
{
id:"aff3b4fa-bdc0-47d1-947f-0163ff5bea06"
keyword: somekeyword
URL:"mypage.html"
}
I need to retrieve the URL value, so I try to get URL by using response.data[0].URL. But I receive the error "Unhandled Rejection (TypeError): response.data[0] is undefined". How do I get the URL value? Thanks.
` autocomplete.js
export class Autocomplete extends Component {
state = {
activeSuggestion: 0,
filteredSuggestions: [],
showSuggestions: false,
userInput: "",
suggestions: [],
results: [],
URL: "",
};
componentDidMount() {
this.GetPrograms();
const { userInput } = this.state;
//this.runSearch();
}
GetPrograms = () => {
axios
.get("https://mydomain/GetPrograms/")
.then((response) => {
this.setState({ suggestions: response.data });
});
};
runSearch = async () => {
const response = await axios.get(
"https://mydomain/api/get",
{
params: {
searchTerm: this.state.userInput,
},
}
);
let results = response.data;
console.log("response", results);
this.setState({ results: results, URL: response.data[0].URL });
window.location.href =
"https://mydomain/" + this.state.URL;
};
onChange = (e) => {
const { suggestions } = this.state; //this.props;
const userInput = e.currentTarget.value;
const filteredSuggestions = suggestions.filter(
(suggestion) =>
suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1
);
this.setState({
activeSuggestion: 0,
filteredSuggestions,
showSuggestions: true,
userInput: e.currentTarget.value,
});
};
onClick = (e) => {
this.setState({
activeSuggestion: 0,
filteredSuggestions: [],
showSuggestions: false,
userInput: e.currentTarget.innerText,
});
this.onSearch();
console.log(
"child component clicked and value=" + e.currentTarget.innerText
);
};
onKeyDown = (e) => {
const { activeSuggestion, filteredSuggestions } = this.state;
if (e.keyCode === 13) {
this.setState({
activeSuggestion: 0,
showSuggestions: false,
userInput: filteredSuggestions[activeSuggestion],
});
} else if (e.keyCode === 38) {
if (activeSuggestion === 0) {
return;
}
this.setState({ activeSuggestion: activeSuggestion - 1 });
} else if (e.keyCode === 40) {
if (activeSuggestion - 1 === filteredSuggestions.length) {
return;
}
this.setState({ activeSuggestion: activeSuggestion + 1 });
}
//this.setState({ searchTerm: e.currentTarget.value });
console.log("userinput:" + this.state.userInput);
};
render() {
const {
onChange,
onClick,
onKeyDown,
onKeyPress,
state: {
activeSuggestion,
filteredSuggestions,
showSuggestions,
userInput,
},
} = this;
let suggestionsListComponent;
if (showSuggestions && userInput) {
if (filteredSuggestions.length) {
suggestionsListComponent = (
<ul class="suggestions">
{filteredSuggestions.map((suggestion, index) => {
let className;
if (index === activeSuggestion) {
className = "";
}
return (
<li key={suggestion} onClick={onClick}>
{suggestion}
</li>
);
})}
</ul>
);
} else {
suggestionsListComponent = (
<div class="no-suggestions">
<em>No suggestions</em>
</div>
);
}
}
return (
<div>
<input
id="search-box"
placeholder="Search..."
type="search"
onChange={onChange}
onKeyDown={onKeyDown}
value={userInput}
/>
{suggestionsListComponent}
</div>
);
}
}
export default Autocomplete;
`
The api call returns 0 record that causes the error.

How to Send message by just clickiing on the suggestion in Botframework-Webchat?

I want my bot to send the message when i click on the desired suggestion. i.e. i want the message to be sent - when i click on the suggestion or by selecting the suggestion using arrow keys and then pressing enter . But as of now, if i click or select the suggestion using arrow keys - the suggestion value comes to the text box and then i have to press enter to send the message. I just want to change that.
Any help would be greatly appreciated
My code is as follows,
import React from 'react';
import { DirectLine, ConnectionStatus } from 'botframework-directlinejs';
import ReactWebChat from 'botframework-webchat';
import './ChatComponent.css';
var val;
var apiParameters = [];
var currentFocus = -1;
export default class extends React.Component {
constructor(props) {
super(props);
this.state = {
token: '',
conversationId: '',
directLine: {},
view: false,
feedBack: null,
value: '',
popupContent: '',
storeValue: '',
suggestions: [],
suggestionCallback: '',
suggestionTypedText: "",
typingChecking: "false",
};
this.handleTokenGeneration = this.handleTokenGeneration.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSaveFeedback = this.handleSaveFeedback.bind(this);
this.handleSuggestion = this.handleSuggestion.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleSuggestionClick = this.handleSuggestionClick.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.moveHighlight = this.moveHighlight.bind(this);
this.getSuggestionHtml = this.getSuggestionHtml.bind(this);
}
getSuggestionHtml(suggestion) {
const lowerCaseSuggestion = suggestion.toLowerCase();
return {
__html: lowerCaseSuggestion.includes(this.state.suggestionTypedText) ? lowerCaseSuggestion
.replace(this.state.suggestionTypedText, `<b>${this.state.suggestionTypedText}</b>`) : lowerCaseSuggestion
};
}
handleTokenGeneration = async () => {
console.log("11111");
const response = await fetch(`api/TokenGenerationService/GetToken`);
const data = await response.json();
this.setState({ token: data.categoryObject.token, conversationId: data.categoryObject.conversationId });
this.state.directLine = new DirectLine({ token: this.state.token });
this.setState({ view: true });
this.setState({ typingChecking: "true" });
console.log("conversationId");
};
async handleSuggestion(val, store) {
if (val === "") {
this.setState({
suggestions: []
});
}
else {
apiParameters = [];
var valuess = null;
const response = await fetch(`api/TokenGenerationService/GetAzureSearch?myparam1=${val}`);
const data = await response.json();
var values = ["Hello", "yes", "no", "exit", "Welcome", "Thank You", "Approve", "Apply leave", "Reject", "Absence Balance", "Leave Balance", "Upcoming Holidays", "Apply Comp-Off", "Approve Leave", "Raise Incident Tickets", "Project Allocation Info", "Reporting Manager Change", "Reporting Manager Approval", "Approve Isolve Tickets", "My Manager", "My Account Manager", "Generate Salary Certificate", "Isolve Ticket Status", "Internal Job Posting", "My Designation", "My Joining Date", "RM Approval", "RM Change", "Resource Allocation", "ESettlement Approval", "SO Approval", "Cash advance Approval", "Purchase Request Approval", "Referral status", "HR Ticket", "Platinum Support"];
valuess = values.filter(s =>
s.toLocaleLowerCase().startsWith(val.toLowerCase())
);
valuess = valuess.concat(data.az_search);
this.setState({
suggestions: valuess,
suggestionCallback: store,
suggestionTypedText: val.toLowerCase()
});
var totCount = data.az_search;
console.log("kkkkkk" + totCount);
var myNode = document.getElementById('Suggestion1');
}
}
getSuggestionCss(index) {
var HIGHLIGHTED_CSS = "HIGHLIGHTED_CSS";
var SUGGESTION_CSS = "SUGGESTION_CSS";
console.log("jioouu" + this.state.highlightedIndex);
return index === this.state.highlightedIndex ? HIGHLIGHTED_CSS : SUGGESTION_CSS;
}
moveHighlight(event, direction) {
event.preventDefault();
const { suggestions, highlightedIndex=-1 } = this.state;
if (!suggestions.length) return;
let newIndex = (highlightedIndex + direction + suggestions.length) % suggestions.length;
console.log("lokkkk" + direction)
if (newIndex !== highlightedIndex) {
console.log("kkkkkkkkkkkkkkkkkkk")
this.setState({
highlightedIndex: newIndex,
});
}
}
keyDownHandlers = {
ArrowDown(event) {
this.moveHighlight(event, 1);
},
ArrowUp(event) {
this.moveHighlight(event, -1);
},
Enter(event) {
const { suggestions } = this.state;
if (!suggestions.length) {
// menu is closed so there is no selection to accept -> do nothing
return
}
event.preventDefault()
this.applySuggestion(suggestions[this.state.highlightedIndex]);
},
}
handleKeyDown(event)
if (this.keyDownHandlers[event.key])
this.keyDownHandlers[event.key].call(this, event)
}
async handleSuggestionClick(event) {
await this.applySuggestion(event.currentTarget.textContent);
}
async applySuggestion(newValue) {
await this.setState({ typingChecking: "false", suggestions: [], highlightedIndex: 0 });
this.state.suggestionCallback.dispatch({
type: 'WEB_CHAT/SET_SEND_BOX',
payload: {
text: newValue,
}
});
await this.setState({ typingChecking: "true" });
}
handleClose(elmnt) {
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt !== x[i]) {
x[i].parentNode.removeChild(x[i]);
}
}
}
async componentDidMount() {
try {
await this.handleTokenGeneration();
const store =
window.WebChat.createStore(
{},
({ getState }) => next => action => {
this.state.directLine.connectionStatus$
.subscribe(connectionStatus => {
//console.log("connect" + connectionStatus);
//console.log("LOP" + ConnectionStatus.ExpiredToken);
if (connectionStatus === ConnectionStatus.ExpiredToken) {
console.log("expired");
}
if (action.type === 'WEB_CHAT/SET_SEND_BOX') {
const val = action.payload.text;
if (this.state.typingChecking === "true") {
this.setState({
highlightedIndex: -1,
});
console.log(this.state.typingChecking);
this.handleSuggestion(val, store);
}
}
if (action.type === 'DIRECT_LINE/DISCONNECT_FULFILLED') {
console.log("final" + connectionStatus);
console.log("finalexpired" + ConnectionStatus.ExpiredToken);
console.log("final");
this.handleTokenGeneration();
// fetch('api/TokenGenerationService/GetToken').then(conversation => this.state.directLine.reconnect(conversation))
}
});
return next(action)
}
);
this.setState({ storeValue: store });
} catch (error) {
console.log("error in fetching token");
console.log(error);
}
this.state.directLine.activity$
.filter(activity => activity.type === 'message')
.subscribe(function (activity)
{
//console.log("oooooooooooooooooooooo");
}
// message => console.log("received message ", message.text)
);
}
handleSaveFeedback(ans) {
var userID = "U92656";
var feedbackmsg = this.state.value;
var feedbacktype = this.state.feedBack;
var convId = this.state.conversationId;
fetch('api/Feedback/SaveFeedback',
{
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ Uid: userID, FeedbackMessage: feedbackmsg, Convid: convId, FeedbackType: feedbacktype })
}).
then(response => response.text())
.then(data => {
console.log(data.getResult);
});
this.setState({ value: '' });
}
feedback(ans) {
this.setState({ feedBack: ans });
if (ans === "Send") {
this.handleSaveFeedback(ans);
}
else if (ans === "Yes") {
this.setState({ popupContent: "How was your experience?" });
// console.log(this.state.value)
}
else if (ans === "No") {
this.setState({ popupContent: "What went wrong?" });
// console.log(this.state.value)
}
}
handleChange = (event) => {
this.setState({ value: event.target.value });
}
render() {
if (!this.state.view) {
return <div />
} else {
const filteredSuggestions = this.state.suggestions.filter(
suggestion =>
suggestion.toLowerCase().indexOf(this.state.suggestionTypedText.toLowerCase()) > -1
);
return (
<div className="react-container webchat" >
<div onKeyDown={this.handleKeyDown.bind(this)}>
<div >
<ReactWebChat directLine={this.state.directLine} webSocket={true} userID='U92656' username='Thomas' store={this.state.storeValue} sendTypingIndicator={true} />
</div>
</div>
<div className="SuggestionParent" id="Suggestion1">
{this.state.suggestions.map((suggestion, index)=> (
<div className={this.getSuggestionCss(index)} key={index} onClick={this.handleSuggestionClick} >
{suggestion
.toLowerCase()
.startsWith(this.state.suggestionTypedText) ? (
<div>
<b>{this.state.suggestionTypedText}</b>
{suggestion
.toLowerCase()
.replace(this.state.suggestionTypedText, "")}
</div>
) : (
<div dangerouslySetInnerHTML={this.getSuggestionHtml(suggestion)} />
)}
</div>
))}
</div>
<footer className="chat-footer" >
<div className="foot-footer">
Was I helpful ?
<span className="feedback" onClick={() => this.feedback("Yes")} >Yes</span><span>|</span><span className="feedback" onClick={() => this.feedback("No")}>No</span>
{
this.state.feedBack === "Yes" || this.state.feedBack === "No" ?
(
<div className="dialog" id="myform">
<div id="textfeedback">
<span id="closeFeedback" onClick={() => this.feedback("Close")}>X</span>
<p>{this.state.popupContent}</p>
<input type="text" id="feedbacktxtbox" required name="textfeedback" placeholder="Pleasure to hear from u!"
onChange={this.handleChange}
value={this.state.value} />
<button type="button" id="btnfeedback" onClick={() => this.feedback("Send")}>send</button>
</div>
</div>
) : null
}
</div>
</footer>
</div>
);
}
}
}

React MenuItem event.target.value not working in one, but works for the other MenuItem

I have two MenuItem drop down menus. The first is for selecting between two items (not working) and the second drop down menu has a list of years, which is working.
The following are the functions that I have created to capture the event.target.value for each of them:
handleYrChange = (event) => {
console.log('handleYrChange: ' + event.target.value);
this.setState({ data: [] });
getPartIdUpperSa(event.target.value).subscribe((res) => {
this.setState({ data: res });
this.setState({ isLoading: false });
});
this.props.isLoading ? this.setState({ isLoading: false }) : this.setState({ isLoading: true });
this.setState({ yrValue: event.target.value });
this.onCloseYr();
}
handleSaChange = (event) => {
console.log('handleSaChange: ' + event.target.value);
if(event.target.value === 'notSa') {
this.setState({ isPartIdUpperSa: false });
} else {
this.setState({ isPartIdUpperSa: true });
}
setBaseUrl(event.target.value);
this.setState({ saValue: event.target.value });
this.onCloseSa();
}
handleYrClick = (event) => {
this.setState({ yrAnchorEl: event.target })
this.setState({ yrOpen: true });
}
handleSaClick = (event) => {
this.setState({ saAnchorEl: event.target })
this.setState({ saOpen: true });
}
The following is a screen shot of when I have tried to click on the items. As you can see, the drop down for years is working as expected, yet the other is capturing "0"
The following is the full component, along with the service that it is subscribed:
First the component:
import React from "react";
import { FormGroup, FormControl, Button, Menu, MenuItem } from '#material-ui/core';
import MUIDataTable from "mui-datatables";
import { MuiThemeProvider } from '#material-ui/core/styles';
import { getPartIdUpperSa } from '../services/part-id-upper-sa-service';
import { setBaseUrl } from '../services/part-id-upper-sa-service'
import theme from '../theme';
export default class ParIdUpperSaComponent extends React.Component {
state = {
data: [],
Header: [],
totalCount: 10,
options: {
pageSize: 16,
page: 0,
filterType: "dropdown",
selectableRows: false,
responsive: "scroll",
resizableColumns: true,
className: this.name,
textLabels: {
body: {
noMatch: this.props.isLoading ?
'' :
'Please wait while processing...',
},
},
},
divAnchorEl: null,
yrValue: '2020',
yrOpen: false,
yrAnchorEl: null,
yrs: [],
saValue: 'sa',
saOpen: false,
saAnchorEl: null,
sa: ["sa","notSa"],
isLoading: true,
isPartIdUpperSa: true
}
componentDidMount() {
// create array of years for the past 18 years
const currentYr = new Date().getFullYear();
for(let x = 0; x < 18; x++) {
this.state.yrs.push(currentYr - x );
}
this.subscription = getPartIdUpperSa().subscribe((res) => {
this.setState({ data: res });
this.props.isLoading ? this.setState({ textLabels: '' }) : this.setState({ textLabels: 'Please wait while processing...' });
this.setState({ isLoading: false });
this.setState({ Header: [
{
label: "Part ID",
name: 'part_id_upper',
options: {
className: 'first-col'
}
},
{
label: "Seq",
name: 'sequence',
options: {
className: 'sec-col'
}
},
{
label: "Qty",
name: 'quantity',
options: {
className: 'sm-col'
}
},
{
label: "Dt Orig",
name: 'date_originated',
options: {
className: 'mid-col'
}
},
{
label: "Div",
name: 'code_division',
options: {
className: 'sm-col'
}
},
]});
this.setState({
totalCount: Math.ceil(this.state.data.length / this.state.pageSize)
});
})
}
componentWillUnmount() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
handleYrChange = (event) => {
console.log('handleYrChange: ' + event.target.value);
// this.setState({value: event.target.value ? event.target.value : ''});
this.setState({ data: [] });
getPartIdUpperSa(event.target.value).subscribe((res) => {
this.setState({ data: res });
this.setState({ isLoading: false });
});
this.props.isLoading ? this.setState({ isLoading: false }) : this.setState({ isLoading: true });
this.setState({ yrValue: event.target.value });
this.onCloseYr();
}
handleSaChange = (event) => {
console.log('handleSaChange: ' + event.target.value);
if(event.target.value === 'notSa') {
this.setState({ isPartIdUpperSa: false });
} else {
this.setState({ isPartIdUpperSa: true });
}
setBaseUrl(event.target.value);
this.setState({ saValue: event.target.value });
this.onCloseSa();
}
handleYrClick = (event) => {
this.setState({ yrAnchorEl: event.target })
this.setState({ yrOpen: true });
}
handleSaClick = (event) => {
this.setState({ saAnchorEl: event.target })
this.setState({ saOpen: true });
}
onCloseYr = () => {
this.setState({ yrOpen: false });
}
onCloseSa = () => {
this.setState({ saOpen: false });
}
render() {
let arrayofSa = this.state.sa;
let saDropDown = arrayofSa.map((sa) =>
<MenuItem onClick={(event) => this.handleSaChange(event)} value={sa} key={sa}>
{sa}
</MenuItem>
);
let arrayOfYrs = this.state.yrs;
let yrDropDown = arrayOfYrs.map((yrs) =>
<MenuItem onClick={(event) => this.handleYrChange(event)} value={yrs} key={yrs}>
{yrs}
</MenuItem>
);
return (
<div>
<MuiThemeProvider theme={theme}>
<FormGroup column='true'>
<FormControl>
<Button aria-controls="simple-menu" aria-haspopup="true" onClick={this.handleSaClick}>
Select Sa or NotToSa
</Button>
<Menu id="sa-menu" open={this.state.saOpen}
anchorEl={this.state.saAnchorEl} onClose={this.onCloseSa}
defaultValue={this.state.saValue ? this.state.saValue : ''} >
{saDropDown}
</Menu>
<Button aria-controls="simple-menu" aria-haspopup="true" onClick={this.handleYrClick}>
Select Year
</Button>
<Menu id="yrs-menu" open={this.state.yrOpen}
anchorEl={this.state.yrAnchorEl} onClose={this.onCloseYr}
defaultValue={this.state.yrValue ? this.state.yrValue : ''} >
{yrDropDown}
</Menu>
</FormControl>
</FormGroup>
</MuiThemeProvider>
{this.state.isLoading ? <img src="ajax-loader.gif" alt="loading gif" /> : ''}
<MUIDataTable
title="Part ID Upper Sa / Not Sa Report"
data={ this.state.data }
columns={ this.state.Header }
options={ this.state.options }
/>
</div>
);
}
}
The following is the service:
import { ajax } from "rxjs/ajax";
import { Observable } from "rxjs";
let base_url = 'https://localhost:5001/PartIdUpperSa';
export const getBaseUrl = () => {
return base_url;
}
export const setBaseUrl = (param) => {
console.log("from within setBaseUrl: " + param);
if(param === 'notSa') {
base_url = 'https://localhost:5001/PartIdUpperNotSa';
} else {
base_url = 'https://localhost:5001/PartIdUpperSa';
}
}
let state = {
data: []
}
export const getPartIdUpperSa = (yr) => {
return new Observable(observe => {
let mYr = new Date().getFullYear();
let tempYr = (yr)? yr : mYr;
state.data = ajax
.get(base_url + "/" + tempYr)
.subscribe(resu => {
state.data = resu.response ;
// console.log("from within getPartIdUpperSa: " + JSON.stringify(resu.response));
observe.next(resu.response);
});
});
}
As usual, thanks in advance
I was able to find a work around. If someone could explain why this works, then I would appreciate it.
The component now uses numbers instead of characters in the array called "sa," which made it function as expected.
I used this:
sa: ["1","2"],
instead of this:
sa: ["sa","notSa"],
And it worked, the following is the complete component:
import React from "react";
import { FormGroup, FormControl, Button, Menu, MenuItem } from '#material-ui/core';
import MUIDataTable from "mui-datatables";
import { MuiThemeProvider } from '#material-ui/core/styles';
import { getPartIdUpperSa } from '../services/part-id-upper-sa-service';
import { setBaseUrl } from '../services/part-id-upper-sa-service'
import theme from '../theme';
export default class ParIdUpperSaComponent extends React.Component {
state = {
data: [],
Header: [],
totalCount: 10,
options: {
pageSize: 16,
page: 0,
filterType: "dropdown",
selectableRows: false,
responsive: "scroll",
resizableColumns: true,
className: this.name,
textLabels: {
body: {
noMatch: this.props.isLoading ?
'' :
'Please wait while processing...',
},
},
},
divAnchorEl: null,
yrValue: '2020',
yrOpen: false,
yrAnchorEl: null,
yrs: [],
saValue: '1',
saOpen: false,
saAnchorEl: null,
sa: ["1","2"],
isLoading: true,
isPartIdUpperSa: true
}
componentDidMount() {
// create array of years for the past 18 years
const currentYr = new Date().getFullYear();
for(let x = 0; x < 18; x++) {
this.state.yrs.push(currentYr - x );
}
this.subscription = getPartIdUpperSa().subscribe((res) => {
this.setState({ data: res });
this.props.isLoading ? this.setState({ textLabels: '' }) : this.setState({ textLabels: 'Please wait while processing...' });
this.setState({ isLoading: false });
this.setState({ Header: [
{
label: "Part ID",
name: 'part_id_upper',
options: {
className: 'first-col'
}
},
{
label: "Seq",
name: 'sequence',
options: {
className: 'sec-col'
}
},
{
label: "Qty",
name: 'quantity',
options: {
className: 'sm-col'
}
},
{
label: "Dt Orig",
name: 'date_originated',
options: {
className: 'mid-col'
}
},
{
label: "Div",
name: 'code_division',
options: {
className: 'sm-col'
}
},
]});
this.setState({
totalCount: Math.ceil(this.state.data.length / this.state.pageSize)
});
})
}
componentWillUnmount() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
handleYrChange = (event) => {
console.log('handleYrChange: ' + event.target.value);
this.setState({ data: [] });
getPartIdUpperSa(event.target.value).subscribe((res) => {
this.setState({ data: res });
this.setState({ isLoading: false });
});
this.props.isLoading ? this.setState({ isLoading: false }) : this.setState({ isLoading: true });
this.setState({ yrValue: event.target.value });
this.onCloseYr();
}
handleSaChange = (event) => {
console.log('handleSaChange: ' + event.target.value);
if(event.target.value === '2') {
this.setState({ isPartIdUpperSa: false });
} else {
this.setState({ isPartIdUpperSa: true });
}
setBaseUrl(event.target.value);
this.setState({ saValue: event.target.value });
this.onCloseSa();
}
handleYrClick = (event) => {
this.setState({ yrAnchorEl: event.target })
this.setState({ yrOpen: true });
}
handleSaClick = (event) => {
this.setState({ saAnchorEl: event.target })
this.setState({ saOpen: true });
}
onCloseYr = () => {
this.setState({ yrOpen: false });
}
onCloseSa = () => {
this.setState({ saOpen: false });
}
render() {
let arrayofSa = this.state.sa;
let saDropDown = arrayofSa.map((sa) =>
<MenuItem onClick={(event) => this.handleSaChange(event)} value={sa} key={sa}>
{sa}
</MenuItem>
);
let arrayOfYrs = this.state.yrs;
let yrDropDown = arrayOfYrs.map((yrs) =>
<MenuItem onClick={(event) => this.handleYrChange(event)} value={yrs} key={yrs}>
{yrs}
</MenuItem>
);
return (
<div>
<MuiThemeProvider theme={theme}>
<FormGroup column='true'>
<FormControl>
<Button aria-controls="simple-menu" aria-haspopup="true" onClick={this.handleSaClick}>
Select Sa or NotToSa
</Button>
<Menu id="sa-menu" open={this.state.saOpen}
anchorEl={this.state.saAnchorEl} onClose={this.onCloseSa}
defaultValue={this.state.saValue ? this.state.saValue : ''} >
{saDropDown}
</Menu>
<Button aria-controls="simple-menu" aria-haspopup="true" onClick={this.handleYrClick}>
Select Year
</Button>
<Menu id="yrs-menu" open={this.state.yrOpen}
anchorEl={this.state.yrAnchorEl} onClose={this.onCloseYr}
defaultValue={this.state.yrValue ? this.state.yrValue : ''} >
{yrDropDown}
</Menu>
</FormControl>
</FormGroup>
</MuiThemeProvider>
{this.state.isLoading ? <img src="ajax-loader.gif" alt="loading gif" /> : ''}
<MUIDataTable
title="Part ID Upper Sa / Not Sa Report"
data={ this.state.data }
columns={ this.state.Header }
options={ this.state.options }
/>
</div>
);
}
}
The following is the service that the component is subscribed to it:
import { ajax } from "rxjs/ajax";
import { Observable } from "rxjs";
let base_url = 'https://localhost:5001/PartIdUpperSa';
export const getBaseUrl = () => {
return base_url;
}
export const setBaseUrl = (param) => {
console.log("from within setBaseUrl: " + param);
if(param == '1') {
base_url = 'https://localhost:5001/PartIdUpperSa';
} else {
base_url = 'https://localhost:5001/PartIdUpperNotSa';
}
}
let state = {
data: []
}
export const getPartIdUpperSa = (yr) => {
return new Observable(observe => {
let mYr = new Date().getFullYear();
let tempYr = (yr)? yr : mYr;
state.data = ajax
.get(base_url + "/" + tempYr)
.subscribe(resu => {
state.data = resu.response ;
observe.next(resu.response);
});
});
}
Once more, if someone could explain why numbers work with event.target.value and characters do not, then I would appreciate it.

How to properly display JSON result in a table via ReactJS

I have this code which fetches data from an API and displays JSON response in a div. How do I display the JSON response in a table?
This is how I display it in div via status.jsx:
// some codings
render() {
const { status, isLocal } = this.props;
if(!isLocal()) {
return (
<div className="status">
<div className="status-text">
<b>Status</b> {status.text}<br />
<b>Title</b> status.textTitle} <br />
<b>Event</b> {status.textEvent}
</div>
</div>
)
}
}
I have tried displaying it in a table as per below but could not get it to be aligned properly
//some codings
render() {
const { status, isLocal } = this.props;
if(!isLocal()) {
return (
<table>
<tbody>
<th>Status</th>
<th>Title</th>
<th>Event</th>
<tr>
<td>{status.text} </td>
<td>{status.textTitle} </td>
<td>{status.textEvent}</td>
<td><button
className="btn btn-danger status-delete"
onClick={this.toggleDeleteConfirmation}
disabled={this.state.showDeleteConfirmation}
>
Delete
</button></td>
</tr></tbody>
</table>
)
}
}
Here is profile.jsx:
import React, { Component } from 'react';
import {
isSignInPending,
loadUserData,
Person,
getFile,
putFile,
lookupProfile
} from 'bs';
import Status from './Status.jsx';
const avatarFallbackImage = 'https://mysite/onename/avatar-placeholder.png';
const statusFileName = 'statuses.json';
export default class Profile extends Component {
constructor(props) {
super(props);
this.state = {
person: {
name() {
return 'Anonymous';
},
avatarUrl() {
return avatarFallbackImage;
},
},
username: "",
statuses: [],
statusIndex: 0,
isLoading: false
};
this.handleDelete = this.handleDelete.bind(this);
this.isLocal = this.isLocal.bind(this);
}
componentDidMount() {
this.fetchData()
}
handleDelete(id) {
const statuses = this.state.statuses.filter((status) => status.id !== id)
const options = { encrypt: false }
putFile(statusFileName, JSON.stringify(statuses), options)
.then(() => {
this.setState({
statuses
})
})
}
fetchData() {
if (this.isLocal()) {
this.setState({ isLoading: true })
const options = { decrypt: false, zoneFileLookupURL: 'https://myapi/v1/names/' }
getFile(statusFileName, options)
.then((file) => {
var statuses = JSON.parse(file || '[]')
this.setState({
person: new Person(loadUserData().profile),
username: loadUserData().username,
statusIndex: statuses.length,
statuses: statuses,
})
})
.finally(() => {
this.setState({ isLoading: false })
})
} else {
const username = this.props.match.params.username
this.setState({ isLoading: true })
lookupProfile(username)
.then((profile) => {
this.setState({
person: new Person(profile),
username: username
})
})
.catch((error) => {
console.log('could not resolve profile')
})
const options = { username: username, decrypt: false, zoneFileLookupURL: 'https://myapi/v1/names/'}
getFile(statusFileName, options)
.then((file) => {
var statuses = JSON.parse(file || '[]')
this.setState({
statusIndex: statuses.length,
statuses: statuses
})
})
.catch((error) => {
console.log('could not fetch statuses')
})
.finally(() => {
this.setState({ isLoading: false })
})
}
}
isLocal() {
return this.props.match.params.username ? false : true
}
render() {
const { handleSignOut } = this.props;
const { person } = this.state;
const { username } = this.state;
return (
!isSignInPending() && person ?
<div className="container">
<div className="row">
<div className="col-md-offset-3 col-md-6">
{this.isLocal() &&
<div className="new-status">
Hello
</div>
}
<div className="col-md-12 statuses">
{this.state.isLoading && <span>Loading...</span>}
{
this.state.statuses.map((status) => (
<Status
key={status.id}
status={status}
handleDelete={this.handleDelete}
isLocal={this.isLocal}
/>
))
}
</div>
</div>
</div>
</div> : null
);
}
}

How to do search in table?

I want to search with all the pagination and sorter field on place.
That is i want to call handleChange with searchkeyword.
So how can i call handleSearch and than call handleChange from within handleSearch?
import React from "react";
import { withRouter } from "react-router-dom";
import { Table, Button, Icon, Row, Col, Input } from "antd";
import axios from "axios";
const Search = Input.Search;
class App extends React.Component {
state = {
data: [],
searchValue: "",
loading: false,
visible: false,
pagination: {}
};
componentDidMount() {
this.fetch();
}
handleTableChange = (pagination, filter, sorter, value) => {
console.log(pagination, value, sorter, "Table Change");
let sorterOrder = "";
let sorterField = "";
let searchVal = "";
const pager = { ...this.state.pagination };
pager.current = pagination.current;
this.setState({
pagination: pager
});
if (value) {
console.log("inside if");
searchVal = undefined;
} else {
console.log("inside else");
searchVal = value;
}
if (sorter) {
if (sorter.order === "ascend") {
sorterOrder = "ASC";
}
if (sorter.order === "descend") {
sorterOrder = "DESC";
}
sorterField = sorter.field;
}
this.fetch({
page: pagination.current,
sortField: sorterField,
sortOrder: sorterOrder,
...filter,
value: searchVal
});
};
fetch = (params = {}) => {
this.setState({ loading: true });
axios.post("***/****", params).then(res => {
const pagination = { ...this.state.pagination };
let apiData = res.data.result;
if (res.data.status === 1) {
const objects = apiData.map(row => ({
key: row.id,
id: row.id,
firstName: row.firstName,
lastName: row.lastName,
status: row.status,
email: row.email
}));
console.log(res.data);
pagination.total = res.data.count;
this.setState({
loading: false,
data: objects,
pagination
});
} else {
console.log("Database status is not 1!");
}
});
};
handleSearch = value => {
console.log("value", value);
this.setState({
searchValue: value
});
let searchkey = this.state.searchValue;
const pagination = { ...this.state.pagination };
const sorter = { ...this.state.sorter };
console.log("search", value, pagination, sorter);
this.handleTableChange({
value
});
};
render() {
const columns = [
{
title: "First Name",
dataIndex: "firstName",
sorter: true
},
{
title: "Email",
dataIndex: "email",
sorter: true
}
];
return (
<div>
<Search
placeholder="input search text"
className="searchBut"
onSearch={value => this.handleSearch(value)}
/>
<Button
className="addBut"
style={{ marginTop: "0" }}
type="primary"
onClick={() => this.openForm()}
>
+ Add Admin
</Button>
</div>
<Table
bordered
columns={columns}
dataSource={this.state.data}
pagination={{ total: this.state.pagination.total, pageSize: 4 }}
loading={this.state.loading}
onChange={this.handleTableChange}
/>
);
}
}
export default withRouter(App);
here when i give value in search field it will call post request with request payload as follows:
{sortField: "", sortOrder: ""}
sortField: ""
sortOrder: ""
So how can i do that?
I'm not sure what you trying of achieve it here.
But you can always filter the source data of the table. Like following
<Table
bordered
columns={columns}
dataSource={this.state.data.filter(data=> Object.keys(data).filter(key => data[key].includes(searchValue)).length > 0 ? true: false)}
pagination={{ total: this.state.pagination.total, pageSize: 4 }}
loading={this.state.loading}
onChange={this.handleTableChange}
/>
let me know if it helps.

Resources