Dynamic navbar using React.js

2.5k views Asked by At

I am trying to create a navbar, in which three components will show but dynamically for example:

if user is not logged in then navbar will show only three components in navlinks and they will be:

  1. About
  2. login
  3. Signup

if user is logged in then navbar will show only three components in navlinks that will be:

  1. About
  2. Dashboard
  3. Logout (i.e a button)

I am new to react and dont know what to do.

What I am doing:

login.jsx

import React from 'react';
import { useContext } from "react";
import { UserContext } from "../UserContext";
import {Link, Redirect} from "react-router-dom";
import "./login.css";

class Login extends React.Component {
    
    constructor(props) {
        super(props);
        this.state = {
            email:"",
            password:"",
            token:"",
            user:[],
            loggedIn:false
        };
    }
    handleChange = (e) => {
        this.setState({ [e.target.name]: e.target.value });
    };

    componentDidMount() {

    }
    
    login = (e) => {
        const {email,password}=this.state;
        const rawurl = 'http://localhost:5000/api/user/login';
        const url = rawurl;
        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email:email,password:password })
        };
        e.preventDefault();
            fetch(url,requestOptions)
                .then(response => response.json())
                .then(data => {
                    console.log(data);
                    this.setState({ user: [data], loaded: true });
                    localStorage.setItem('userData',JSON.stringify(this.state.user));
                    localStorage.setItem('token',JSON.stringify(this.state.user[0].token))
                    this.setState({token:localStorage.getItem('token')})
                    console.log(localStorage.getItem('userData'));
                    this.setState({loggedIn:true});
                })
                .catch(err => console.log("error ", err))

    }
    render() {
        if(this.state.loggedIn==true){
            return <Redirect to="/dashboard/read"></Redirect>
        } 
        return (
            <div id="login">
                <div class="slide-in-elliptic-right-fwd">
                    Welcome to Login Page
                </div><br/>
                <div id="loginForm" class="scale-in-hor-center">
                    <form>
                        <input type="email" name="email" value={this.state.email} placeholder="Email" onChange={this.handleChange}></input>
                        <input type="password" name="password" value={this.state.password} placeholder="Password" onChange={this.handleChange}></input>
                        <button onClick={this.login} id="loginButton" class="bounce-in-top">Login</button>
                        ........or........
                       <Link to="/signup" class="bounce-in-top">Signup</Link>
                    </form>
                </div>
            </div>
        );
    }
}
export default Login;

navbar.jsx

import React from 'react';
import { useContext } from "react";
import { UserContext } from "../UserContext";
import {Link} from "react-router-dom";
import "./navbar.css";
function Navbar() {
    const { user } = useContext(UserContext);
    if(user!=null){
        return(
            <div id="navbar">
            <div class="tracking-in-contract-bck">
                Blogs4You
            </div>
            <div id="navLinks">
                <Link to="/about">About</Link>
                ||
                <Link to="/">Logout</Link>
            </div>
        </div> 
        );
    }
    else{
        return (
            <div id="navbar">
                <div class="tracking-in-contract-bck">
                    Blogs4You
                </div>
                <div id="navLinks">
                    <Link to="/about">About</Link>
                    ||
                    <Link to="/login">Login</Link>
                    ||or||
                    <Link to="/signup">Signup</Link>
                </div>
            </div>
        );
    }
}
export default Navbar;

I have two things in mind i.e. to use api context and the other is localstorage. Kindly help me in solving this problem.

1

There are 1 answers

0
Harsh Nasit On

You can use ternary operation for this type of situation. For this follow the steps

  1. when the user login store the user data in local storage. eg localStorage.setItem("key", JSON.stringify(userData).

  2. Now in navbar.jsx you can use ternary operation statement like eg. { (boolean satement)? (code if true):(code if false)}. By using this you can get user info and can use is inside boolean statement of ternary opration. for your navbar here is an example..

import React from 'react';
import { useContext } from "react";
import { UserContext } from "../UserContext";
import {Link} from "react-router-dom";
import "./navbar.css";
function Navbar() {
    const { user } = useContext(UserContext);
    
    {(user!=null)?
        (
            <div id="navbar">
            <div class="tracking-in-contract-bck">
                Blogs4You
            </div>
            <div id="navLinks">
                <Link to="/about">About</Link>
                ||
                <Link to="/">Logout</Link>
            </div>
        </div> 
        );
   :
     (
            <div id="navbar">
                <div class="tracking-in-contract-bck">
                    Blogs4You
                </div>
                <div id="navLinks">
                    <Link to="/about">About</Link>
                    ||
                    <Link to="/login">Login</Link>
                    ||or||
                    <Link to="/signup">Signup</Link>
                </div>
            </div>
        );
    
}
export default Navbar;