Ad

React Router With Admin Layout

- 1 answer

I have developed a mini web-portal which has a react based form for saving records and a retrieval page to search those records / delete and edit them.. When I click edit. Then I want my form to get open which can be done through routers.

I have have routed to my form page but it is hiding all the panels and menus and showing just the page. Can anybody help what am I doing wrong with the router?

Retrieval JSX file

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);  
  }

  // 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.props.history.push('/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} 
                                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;

Form JSX File


import React, { Component } from "react";
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() {
    super()
    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}>
              <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;

** Router file **

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";

ReactDOM.render(
  <BrowserRouter>
    <Switch>
      <Route path="/admin" render={props => <AdminLayout {...props} />} />
      <Route path='/userProfile' component={UserProfile} />
      <Redirect from="/" to="/admin/dashboard" />
    </Switch>
  </BrowserRouter>,
  document.getElementById("root")
);

Ad

Answer

If you want to prevent other components from disappearing, you need to adjust your path accordingly. For example: path='/admin shows panels and menus and admin welcome page, right? Then you need to create a path like this path='/admin/edit' for your panels and menus to show up in your edit route.

Ad
source: stackoverflow.com
Ad