Arebhy Sridaran
Arebhy Sridaran

Reputation: 586

How to pass the username into multi pages in reactjs

I'm totally new to reactjs. I have successfully created user register tab and login tab also. problem is after login; the username should be show into the nav bar. As my site I have created nav bar page(NavBar.js) and login page (Login.js) separately As my learn sessionStorage and props can possible for this. but I'm totally confused how to use it. please anyone give hint to solve my problem. my backend is loopback This is my login.js

const FormItem = Form.Item;

    export default class Login extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          email: "",
          password: "",
          details: ""
        };
      }

      handleChange = event => {
        this.setState({ [event.target.name]: event.target.value });
      };

      onSubmit(e) {
        var email = this.state.email;
        var password = this.state.password;
        axios
          .get(
            `http://localhost:3000/api/UserLogins/findOne?filter={"where":{"email":"${email}"}}`
          )
          .then(response => {
            this.setState({ details: response.data }, () => {
              if (password === this.state.details.password) {
                console.log("login");
              } else {
                console.log("not login");
              }
            });
          })
          .catch(err => console.log(err));
        e.preventDefault();
      }

      render() {
        let UserLoginDetail = this.state.details.username;
        sessionStorage.setItem(UserLoginDetail, this.state.details.username);

        return (
          <div>
            <form onSubmit={this.onSubmit.bind(this)}>
              <FormItem>
                <Input
                  onChange={this.handleChange}
                  prefix={<Icon type="mail" style={{ color: "rgba(0,0,0,.25)" }} />}
                  name="email"
                  type="email"
                  placeholder="[email protected]"
                />
              </FormItem>
              <FormItem>
                <Input
                  onChange={this.handleChange}
                  prefix={<Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />}
                  name="password"
                  type="password"
                  placeholder="Password"
                />
              </FormItem>
              <FormItem>
                <Checkbox>Remember me</Checkbox>
                <a className="login-form-forgot" href="">
                  Forgot password
                </a>
                <Button
                  type="primary"
                  htmlType="submit"
                  className="login-form-button"
                >
                  Log in
                </Button>
              </FormItem>
            </form>
          </div>
        );
      }
    }

NavBar.js code is

import React from 'react';
import 'antd/dist/antd.css';
import 'bootstrap/dist/css/bootstrap.css';
import { Collapse,Navbar,NavbarToggler,NavbarBrand,Nav,NavItem,NavLink} from 'reactstrap';
import ResizeImage from 'react-resize-image';
import { Row, Col } from 'antd';
import { Modal, Button } from 'antd';
import { Tabs,Icon } from 'antd';
import Login from './Login';
import Register from './Register';

const TabPane = Tabs.TabPane;

function callback(key) {
  console.log(key);
}

export default class NavBar extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      isOpen: false,
    };
  }
  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }

  state = { visible: false }

  showModal = () => {
    this.setState({
      visible: true,
    });
  }

  handleOk = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  }

  handleCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  }

  render() {
    let myItem = sessionStorage.getItem('userName');
    return (
      <Row className="vert-align">
      <Col push={24}>
      <div>
        <Navbar color="light" white="true" expand="md">
          <NavbarBrand href="/">
          <ResizeImage
            src={require('../image/logo.png')}
            alt="logo"

          />
      </NavbarBrand>
        <NavbarToggler onClick={this.toggle} />
          <Collapse isOpen={this.state.isOpen} navbar>
            <Nav className="ml-auto" navbar>
              <NavItem>
                <NavLink href="/">Home</NavLink>
              </NavItem>
              <NavItem>
                <NavLink href="/Car">All Cars</NavLink>
              </NavItem>
              <NavItem>
                <NavLink href="/Rate">Rates</NavLink>
              </NavItem>
              <NavItem>
                <NavLink href="/About">About Us</NavLink>
              </NavItem>
              <NavItem>
                <NavLink href="/BecomePartner"><Icon type="team" />  Become a Partner</NavLink>
              </NavItem>
              <p>{myItem}</p>
              <div>
                <Button type="default" onClick={this.showModal}>
                  <Icon type="login" />Login
                </Button>

                <Modal
                  visible={this.state.visible}
                  onCancel={this.handleCancel}
                  onOk={this.handleOk}
                >
                  <Tabs defaultActiveKey="1" onChange={callback}>
                    <TabPane tab="Login" key="1"><Login/>
                    </TabPane>
                    <TabPane tab="Register" key="2"><Register/></TabPane>
                  </Tabs>
                </Modal>

              </div>

            </Nav>
          </Collapse>
        </Navbar> 
      </div>
      </Col >
      </Row >
    );
  }
}

Upvotes: 1

Views: 3983

Answers (1)

Sahil Arora
Sahil Arora

Reputation: 491

In Login File use SessionStorage in this way:-

sessionStorage.setItem('UserName', this.state.details.username);

In current code you are using key as this.state.details.username and value as this.state.details.username.

Key Should always be fixed,it should not be dependent upon user input,so that you can use it to fetch the value.

After NavBar Code Shared :-

This code should be placed inside

 axios
 .get(
  `http://localhost:3000/api/UserLogins/findOne?filter={"where":{"email":"${email}"}}`
          )
     .then(response => {
      this.setState({ details: response.data }, () => {
       if (password === this.state.details.password) {
        console.log("login");
        sessionStorage.setItem('UserName', this.state.details.username);
        this.props.handeLogin(); 
        /*It will change state of NavBar 
         Component,and it would be re-rendered.
         So,we will get new User Name from 
         session.*/

       } else {
          console.log("not login");
          }
        });
          })

Session Value should be set inside this axios call is because here the value is changing, It should not be assigned in render method,because render method would be called each time state changes.

In Nav File fetch user name :- sessionStorage.getItem('userName');

In Navfile add state property isLoggedIn,

 this.state = {
      isOpen: false,
      isLoggedIn:false
    };

Then add method handlelogin() :-

handleLogin=()=>{
   this.setState({
      isLoggedIn:true
    })
}.

We followed the process of changing state, because Nav Component would not re-render even the SessionStorage userName changes.

In case, userName is required in another components it could be fetched using :- sessionStorage.getItem('userName');

If You Plan to use Redux for State Management visit :- https://redux.js.org/.

Redux is based upon Single Source of Truth.It's like a component for example, Login would update redux store with new userName and the NavBar component will get the updated userName as it would have subscribed to store.

Hope this helps,

Cheers !!

Upvotes: 4

Related Questions