I have created a react application and on a click of one button I am opening my form with props being passed into it.
But when I print the props => match.params values from my form page after routing.. its displaying a null array..
My Router
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import "./assets/css/animate.min.css";
import "./assets/sass/light-bootstrap-dashboard-react.scss?v=1.3.0";
import "./assets/css/demo.css";
import "./assets/css/pe-icon-7-stroke.css";
import AdminLayout from "layouts/Admin.jsx";
import UserProfile from "views/UserProfile";
import Sidebar from "components/Sidebar/Sidebar";
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route path="/admin" render={props => <AdminLayout {...props} />} />
<Route exact path="/admin/userProfile" render={props => <UserProfile {...props} />}/>
<Redirect from="/" to="/admin/dashboard" />
</Switch>
</BrowserRouter>,
document.getElementById("root")
);
My page from where I hit edit button
/*!
=========================================================
* Light Bootstrap Dashboard React - v1.3.0
=========================================================
* Product Page: https://www.creative-tim.com/product/light-bootstrap-dashboard-react
* Copyright 2019 Creative Tim (https://www.creative-tim.com)
* Licensed under MIT (https://github.com/creativetimofficial/light-bootstrap-dashboard-react/blob/master/LICENSE.md)
* Coded by Creative Tim
=========================================================
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
import React, { Component } from "react";
import { BrowserRouter as Router, Route} from 'react-router-dom'
import { Grid, Row, Col, Table } from "react-bootstrap";
import Card from "components/Card/Card.jsx";
import { thArray } from "variables/Variables.jsx";
import { FormInputs } from "components/FormInputs/FormInputs.jsx";
import Button from "components/CustomButton/CustomButton.jsx";
import NotificationSystem from "react-notification-system";
import UserProfile from "./UserProfile";
class TableList extends Component {
constructor(props) {
super(props)
this.state = {
error: null,
transaction: [],
defaultTransactionState: [],
_notificationSystem: null
}
this.editEntry = this.editEntry.bind(this);
this.onChange = this.onChange.bind(this);
}
onChange(e){
this.setState({[e.target.name]: [e.target.value]});
}
// values on page loadup..
componentDidMount() {
const apiUrl = 'http://localhost:3000/api/str/';
fetch(apiUrl)
.then( (response) => {
return response.json();
})
.then((data) => {
this.setState({ transaction: data.response })
this.setState({ defaultTransactionState: data.response })
})
.catch((error) => console.log(error));
}
handleNotificationClick = position => {
var color = Math.floor(Math.random() * 4 + 1);
var level;
switch (color) {
case 1:
level = "success";
break;
case 2:
level = "warning";
break;
case 3:
level = "error";
break;
case 4:
level = "info";
break;
default:
break;
}
this.state._notificationSystem.addNotification({
title: <span data-notify="icon" className="pe-7s-gift" />,
message: (
<div>Challan Deleted Successfully!
</div>
),
level: level,
position: position,
autoDismiss: 5
});
};
editEntry = () => {
console.log("in edit => " + this.state.transaction)
this.props.history.push('/admin/userProfile');
}
deleteEntry = challanNo => {
const transactions = this.state.transaction;
console.log('inside delete.. with Challan No' + challanNo)
const requestOptions = {
method: 'DELETE'
};
this.setState({
transaction: transactions.filter(trn => trn.CHALLAN_NO !== challanNo)
})
fetch("http://localhost:3000/api/str/delete/" + challanNo, requestOptions)
.then((response) => {
return response.json();
})
.then((data) => {
console.log('Done with delete.. Now: ' + typeof data.response)
this.handleNotificationClick(1)
// this.setState({ transaction: data.response })
})
.catch((error) => console.log(error));
}
// reset the rows on backspace..
onKeyDown = (e) => {
if (e.keyCode === 8) {
this.setState({ transaction: this.state.defaultTransactionState })
console.log('delete');
}
}
// filter data set on change event of field values..
filterChallan = (event) => {
console.log(this.state.transaction)
let transaction = this.state.transaction
transaction = transaction.filter((challan) => {
let challanNo = challan.CHALLAN_NO
console.log(event.target.value)
return challanNo.toString().search(event.target.value) !== -1
})
this.setState({
transaction: transaction
})
}
filterEntityName = (event) => {
console.log(this.state.transaction)
let transaction = this.state.transaction
transaction = transaction.filter((challan) => {
let entityName = challan.ENTITY_NAME
console.log(event.target.value)
return entityName.toString().toLowerCase().search(event.target.value.toLowerCase()) !== -1
})
this.setState({
transaction: transaction
})
}
render() {
return (
<div className="content">
<Grid fluid>
<Row>
<Col md={12}>
<Card
title="Filter Criteria"
category="Search the Fee Payment Details for Specific Challan Info"
ctTableFullWidth
ctTableResponsive
content={
<div
style={{ paddingLeft: 12, paddingRight: 0 }}>
<FormInputs
ncols={["col-md-2", "col-md-4"]}
properties={[
{
label: "Challan #",
type: "text",
bsClass: "form-control",
placeholder: "Challan #",
onChange: this.filterChallan,
onKeyDown: this.onKeyDown
},
{
label: "Entity Name",
type: "text",
bsClass: "form-control",
placeholder: "Entity Name",
onChange: this.filterEntityName,
onKeyDown: this.onKeyDown
}
]}
/>
<Table striped hover>
<thead>
<tr>
{thArray.map((prop, key) => {
return <th key={key}>{prop}</th>;
})}
</tr>
</thead>
<tbody>
{this.state.transaction.map((str) => (
<tr key={str.CHALLAN_NO}>
<td>{str.CHALLAN_NO}</td>
<td>{str.ENTITY_NAME}</td>
<td>{str.ENTITY_TYPE}</td>
<td>{str.CITY}</td>
<td>{str.EMAIL}</td>
<td>
<Button bsStyle="info" fill onClick={this.editEntry} onChange={this.onChange}
className="btn btn-primary btn-sm mr-2">
Edit
</Button> <Button bsStyle="info" fill onClick={() => this.deleteEntry(str.CHALLAN_NO)}
className="btn btn-primary btn-sm mr-2">
Delete
</Button>
</td>
</tr>
))}
</tbody>
</Table>
</div>
}
/>
</Col>
</Row>
</Grid>
</div>
);
}
}
export default TableList;
my page which is routed to
/*!
=========================================================
* Light Bootstrap Dashboard React - v1.3.0
=========================================================
* Product Page: https://www.creative-tim.com/product/light-bootstrap-dashboard-react
* Copyright 2019 Creative Tim (https://www.creative-tim.com)
* Licensed under MIT (https://github.com/creativetimofficial/light-bootstrap-dashboard-react/blob/master/LICENSE.md)
* Coded by Creative Tim
=========================================================
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
import React, { Component } from "react";
import backbone from "assets/img/cdc-backbone.jpg";
import {
Grid,
Row,
Col,
FormGroup,
ControlLabel,
FormControl
} from "react-bootstrap";
import { Card } from "components/Card/Card.jsx";
import { FormInputs } from "components/FormInputs/FormInputs.jsx";
import { UserCard } from "components/UserCard/UserCard.jsx";
import Button from "components/CustomButton/CustomButton.jsx";
import avatar from "assets/img/faces/face-3.jpg";
class UserProfile extends Component {
constructor(props) {
super(props)
console.log('props => ' + JSON.stringify(this.props.match.params))
this.state = {
challan_no: '',
challan_amount: '',
entity_name: '',
entity_address: '',
city: '',
district: '',
province: '',
telephone: null,
mobile: null,
email: '',
entity_type: '',
registraton_no: null,
registering_authority_name: '',
principal_lob: ''
}
this.onChange = this.onChange.bind(this)
this.insertRecord = this.insertRecord.bind(this)
}
onChange(e){
this.setState({[e.target.name]: [e.target.value]})
}
insertRecord(event) {
event.preventDefault();
fetch('http://localhost:3000/api/str/insert', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify( {
challan_no: this.state.challan_no,
challan_amount: this.state.challan_amount,
entity_name: this.state.entity_name,
entity_address: this.state.entity_address,
city: this.state.city,
district: this.state.district,
province: this.state.province,
telephone: this.state.telephone,
mobile: this.state.mobile,
email: this.state.email,
entity_type: this.state.entity_type,
registration_no: this.state.registration_no,
registering_authority_name: this.state.registering_authority_name,
principal_lob: this.state.principal_lob
})
}).then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));
}
render() {
return (
<div className="content">
<Grid fluid>
<Row>
<Col md={8}>
<Card
title="Add Fee Payment Details"
content={
<form>
<FormInputs
ncols={["col-md-5", "col-md-3", "col-md-4"]}
properties={[
{
label: "Challan #",
type: "text",
name: "challan_no",
bsClass: "form-control",
placeholder: "Challan #",
value: this.state.challan_no,
onChange: this.onChange
},
{
label: "Challan Amount",
type: "number",
name: "challan_amount",
bsClass: "form-control",
placeholder: "Challan Amount",
value: this.state.challan_amount,
onChange: this.onChange
},
{
label: "Entity Name",
type: "text",
name: "entity_name",
bsClass: "form-control",
placeholder: "Entity Name",
value: this.state.entity_name,
onChange: this.onChange
}
]}
/>
<FormInputs
ncols={["col-md-6", "col-md-6"]}
properties={[
{
label: "Entity Address",
type: "text",
name: "entity_address",
bsClass: "form-control",
placeholder: "Entity Address",
value: this.state.entity_address,
onChange: this.onChange
},
{
label: "City",
type: "text",
name: "city",
bsClass: "form-control",
placeholder: "City",
value: this.state.city,
onChange: this.onChange
}
]}
/>
<FormInputs
ncols={["col-md-6", "col-md-6"]}
properties={[
{
label: "District",
type: "text",
name: "district",
bsClass: "form-control",
placeholder: "District",
value: this.state.district,
onChange: this.onChange
},
{
label: "Province",
type: "text",
name: "province",
bsClass: "form-control",
placeholder: "Province",
value: this.state.province,
onChange: this.onChange
}
]}
/>
<FormInputs
ncols={["col-md-4", "col-md-4", "col-md-4"]}
properties={[
{
label: "Telephone",
type: "number",
name: "telephone",
bsClass: "form-control",
placeholder: "Telephone",
value: this.state.telephone,
onChange: this.onChange
},
{
label: "Mobile",
type: "number",
name: "mobile",
bsClass: "form-control",
placeholder: "Mobile",
value: this.state.mobile,
onChange: this.onChange
},
{
label: "Email",
type: "text",
name: "email",
bsClass: "form-control",
placeholder: "Email",
value: this.state.email,
onChange: this.onChange
}
]}
/>
<FormInputs
ncols={["col-md-4", "col-md-4", "col-md-4"]}
properties={[
{
label: "Entity Type",
type: "text",
name: "entity_type",
bsClass: "form-control",
placeholder: "Entity Type",
value: this.state.entity_type,
onChange: this.onChange
},
{
label: "Registration #",
type: "text",
name: "registration_no",
bsClass: "form-control",
placeholder: "Registration #",
value: this.state.registraton_no,
onChange: this.onChange
},
{
label: "Registration Authority Name",
type: "text",
name: "registering_authority_name",
bsClass: "form-control",
placeholder: "Registration Authority Name",
value: this.state.registering_authority_name,
onChange: this.onChange
}
]}
/>
<Row>
<Col md={12}>
<FormGroup controlId="formControlsTextarea">
<ControlLabel>Principal Line of Business</ControlLabel>
<FormControl
rows="5"
componentClass="textarea"
bsClass="form-control"
name="principal_lob"
value={this.state.principal_lob}
onChange= {this.onChange}
placeholder="Enter the details of your Principal Line of Business"
/>
</FormGroup>
</Col>
</Row>
<Button bsStyle="info" pullRight fill onClick={this.insertRecord}>
Save
</Button>
<div className="clearfix" />
</form>
}
/>
</Col>
<Col md={4}>
<div class="row">
<div class="col-md-12">
<div class="thumbnail">
<img src={backbone} alt="CDC Pakistan" />
<div class="caption">
<h4>Secure Transacton Registry</h4>
<p>Central Depository Company of Pakistan is starting up their new project..</p>
<p><a href="#" class="btn btn-primary" role="button">More Details</a> </p>
</div>
</div>
</div>
</div>
</Col>
{/* <Col md={4}>
<UserCard
bgImage="https://ununsplash.imgix.net/photo-1431578500526-4d9613015464?fit=crop&fm=jpg&h=300&q=75&w=400"
avatar={avatar}
name="Mike Andrew"
userName="michael24"
description={
<span>
"Lamborghini Mercy
<br />
Your chick she so thirsty
<br />
I'm in that two seat Lambo"
</span>
}
socials={
<div>
<Button simple>
<i className="fa fa-facebook-square" />
</Button>
<Button simple>
<i className="fa fa-twitter" />
</Button>
<Button simple>
<i className="fa fa-google-plus-square" />
</Button>
</div>
}
/>
</Col> */}
</Row>
</Grid>
</div>
);
}
}
export default UserProfile;
2
Answers
console.log('props => ' + JSON.stringify(this.props.match.params))
use this line in componentDidMount() or any other function instead of using it in a constructor.you can use custom hook
Copied from https://usehooks.com/useRouter/
“If you use React Router you might have noticed they recently added a number of useful hooks, specifically useParams, useLocation, useHistory, and use useRouteMatch. But let’s see if we can make it even simpler by wrapping them up into a single useRouter hook that exposes just the data and methods we need. In this recipe we show how easy it is to compose multiple hooks and combine their returned state into a single object. It makes a lot of sense for libraries like React Router to offer a selection of low-level hooks, as using only the hook you need can minimize unnecessary re-renders. That said, sometimes you want a simpler developer experience and custom hooks make that easy.”