Transforming the NavBar in React: A guide to dynamically updating values

I am facing an issue with my NavBar that changes based on certain events. The current setup works fine, but I don't want to render it in every class that loads a new page. Initially, I had the NavBar rendering inside App.js so it could appear on all pages, but I struggled with passing values to change it correctly. I'm looking for a solution where I don't have to pass the same variables to every class that loads a new page. How can I resolve this?

Here is the code for my NavBar:

import React from 'react';
import '../App.css';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';

export default function NavBar(props){

    const logged = props.logged;
    const baseTabs = props.baseTabs;

    return (
        <nav>
            <Link style={{color: 'white', textDecoration: 'none'}} to='/'>
                <h3>Aura Flows</h3>
            </Link>

            <ul className='nav-links'>

            {baseTabs && <Link style={{color: 'white', textDecoration: 'none'}} to='/faq'> <li>FAQ</li> </Link> }

            {baseTabs && <Link style={{color: 'white', textDecoration: 'none'}} to='/pricing'> <li>Pricing</li> </Link> }

            {!logged && <Link style={{color: 'white', textDecoration: 'none'}} to='/login'> <li>Login</li> </Link> }

            {!logged && <Link style={{color: 'white', textDecoration: 'none'}} to='/signup'> <li>Sign Up</li> </Link> }

            {logged && <Link style={{color: 'white', textDecoration: 'none'}} to='/logout'> <li>Logout</li> </Link> }

            </ul>

        </nav>
    );
}

NavBar.propTypes = {
    logged: PropTypes.bool.isRequired,
    baseTabs: PropTypes.bool.isRequired
}

One Class that dynamically changes NavBar values:

import React, {useState} from 'react';
import { Redirect } from 'react-router-dom';
import { Link } from 'react-router-dom';
import { auth } from "../Components/firebase";
import '../App.css';
import '../css/SignUp.css';
import NavBar from '../Components/NavBar';


function SignUpPage(){
  const [logged, setLogged] = useState(false);
  const [baseTabs, setBaseTabs] = useState(true);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  const signup = event => {
    event.preventDefault();
    console.log("Sign Up function");
    console.log(username + password)
    auth.createUserWithEmailAndPassword(username, password).then(cred => {
      // console.log(cred.user)
    })
    setBaseTabs(true);
    setLogged(true);
  }


  if(logged === true){
        return (<Redirect to='/home'/>)
  }


  return (
    <div>
      <NavBar logged={logged} baseTabs={baseTabs}/>
      <form className='signUpBox' id='signup-form'>
        <h1>Sign Up</h1>
        <input type='text' name='username' placeholder='Username' onChange={ e => {setUsername(e.target.value)}} required/>
        <input type='password' name='password' placeholder='Password' onChange={ e => {setPassword(e.target.value)}} required/>
        <input type='password' name='confirmPassword' placeholder='Confirm Password' onChange={ e => {setConfirmPassword(e.target.value)}} required/>
        <input type='submit' name='' value='Sign Up' onClick={signup}/>
      </form>
    </div>    
  );
}

Answer №1

Utilizing the principles of state management using the useContext hook or implementing Redux can greatly benefit your project.
I came across a helpful YouTube video that addresses a similar issue to what you are facing.
Feel free to check out this informative video here

Answer №2

When developing a small React application that does not demand extensive global state management, opt for Context API.

For projects requiring robust global state management, consider utilizing Redux instead.

Answer №3

Managing state can be made easier with the help of a user-friendly library.

  1. npm i shared-reducer-hooks
  2. Establish a store
// src/redux/appStatus.js
import SharedReducer from 'shared-reducer-hooks';

const initialState = {
  logged: false,
  showBaseTabs: false
};
const [mapState, dispatch] = SharedReducer((state = initialState, action) => {
  switch(action.type) {
    case 'login':
      return { ...state, logged: true };
    case 'toggleBaseTabs':
      return { ...state, showBaseTabs: action.showBaseTabs };
    default:
      return state;
  }
});

export const useLogged = mapState((state) => state.logged);
export const useShowBaseTabs = mapState((state) => state.showBaseTabs);

export const loginAction = () => dispatch({ type: 'login' });
export const toggleBaseTabsAction = (showBaseTabs) => dispatch({ type: 
'toggleBaseTabs', showBaseTabs });
  1. Utilize in NavBar
// NavBar
import { useLogged, useShowBaseTabs } from '../redux/appStatus';

export default function NavBar() {
  const logged = useLogged();
  const showBaseTabs = useShowBaseTabs();
  //...
}
  1. Implement in SignUpPage
// ...
import { useLogged, loginAction, toggleBaseTabsAction } from '../redux/appStatus';


function SignUpPage() {
    //...
    const logged = useLogged();

    const signup = event => {
    // Doesn't clear fields and allows viewing JSON info in console
    event.preventDefault();
    console.log("Sign Up function");
    console.log(username + password)
    auth.createUserWithEmailAndPassword(username, password).then(cred => {
      // console.log(cred.user)
      loginAction(true);
      toggleBaseTabsAction(true);
    })
  }

  if (logged) {
    return <Redirect to="/home" />;
  }

  return (
    <div>
      <NavBar />
      // ...
    </div>
  );
}

We hope this information proves helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Include personalized headers to the 'request'

I have configured my express server to proxy my API using the following setup: // Proxy api calls app.use('/api', function (req, res) { let url = config.API_HOST + req.url req.pipe(request(url)).pipe(res) }) In this instance, confi ...

Warning: Update state in React-router-redux after redirection

I am currently developing an admin app for a project using react, redux, react-router, and react-router-redux. The version of react-router I am working with is v4.0.0, while react-router-redux is at v5.0.0-alpha.3 (installed with npm install react-router-r ...

The rounded corners feature of PIE.htc does not seem to be functioning properly on Internet Explorer

Check out my code below: http://jsfiddle.net/parag1111/s5RLb/ Make sure to place PIE.htc in the CSS folder. I've already included the necessary JS and behavior for PIE.htc. Please provide any additional suggestions to ensure compatibility with IE8 a ...

Using JavaScript to dynamically calculate the sum of selected column values in Angular Datatables

I have a table set up where, if a checkbox is checked, the amounts are automatically summed and displayed at the top. However, I am encountering issues with the code below as it is not providing the exact sum values. Can anyone suggest a solution to this p ...

What is the best way to retrieve data from localStorage while using getServerSideProps?

I'm currently developing a next.js application and have successfully integrated JWT authentication. Each time a user requests data from the database, a middleware function is triggered to validate the req.body.token. If the token is valid, the server ...

Waiting for the result of an AngularJS promise

When I click a button in my AngularJS app, the following code is executed: if (!$scope.isChecked) { $scope.getExistingName($scope.userName).then(function (data) { $scope.userName = data; }); } // Additional processing code foll ...

Tips on implementing a jQuery .load() function using an anchor tag within dynamic content

I am working on a search page where user input is taken from a form and then sent to a PHP file that makes a cURL call to an external server. The PHP file receives an array from the server, which it uses to display HTML in a "results" div on the original s ...

Hovering over the child element, instead of the parent

I'm working on implementing a highlight feature for my website. The structure of the HTML looks something like this: <div> <!-- this is the main container --> <div> content ... </div><!-- a child element --> < ...

A data type labeled as 'undefined' needs to include a method called '[Symbol.iterator]()' which will then return an iterator

I've been working on converting my reducer from JavaScript to TypeScript, but I keep encountering a strange error that I can't seem to resolve. The issue arises when I attempt to use ellipsis for array deconstruction in the reducer [...state.mess ...

Activate a webpage upon enabling/disabling a Chrome extension

In my current setup within the useEffect of my React component, I have a setInterval function set to run every second. This function calls chrome.runtime.sendMessage() to listen for messages from a Chrome extension. In the background script of the Chrome e ...

Using a navigation bar as a structural component in React

I have a new app in development that features a search bar on every page as part of the layout. When a user conducts a search, the results are displayed and they can click on a result to view more details in a separate component. My main question is regar ...

Browsing through an array of objects in PHP

Currently working on creating an array of objects using jQuery. var selected_tests = $("#selected_tests").find("tr"); jsonLab = []; $.each(selected_tests, function() { jsonLab.push({ test: ($(this).children()).eq(0).text(), amount: ($(this).chil ...

Scripts in iframes within webviews are not preloading and executing properly

When using the <webview> tag in the renderer process within the <body> of a web page, the following code is used: <webview src="http://somewebpage.com" preload="somescript.js"> The script somescript.js will be execute ...

React JS - State values are not persisting and rendering properly upon clicking

Recently, I followed a step-by-step tutorial on creating a todo list using functional components. However, I encountered an issue when attempting to delete or mark items as complete in the list. In both the deleteHandler and completeHandler functions, I tr ...

Is it possible to scroll only a portion of a div element without relying on absolute positioning and when the

HTML: <div class="block"> <div class="header">Some text</div> <div class="content"> <p> Unique content goes here. </p> <p> More unique content for demonstration ...

What is the reason for JavaScript consistently returning the initial value as the result?

My current issue involves customizing Joomla article content using a module. I am attempting to hide a div until a user clicks on an input, such as a radio button labeled Test1. Once Test1 is selected, another hidden field within the div should display the ...

Creating a Higher Order Component (HOC) for your Next.js page

Upon running the following code, I encountered an error message Error: The default export is not a React Component in page: "/" pages/index.tsx import React, { useState, useRef } from "react"; import type { NextPage } from "next&q ...

Chrome compatibility problem with scroll spy feature in Bootstrap 3

Having trouble with scroll spy for boosters using the body method " data-spy="scroll". It seems to be working for some browsers like Edge and Google Chrome, but after multiple attempts, it still doesn't work for me. Even after asking friends to test i ...

Issue with popup display in React Big Calendar

I'm currently working on a calendar project using React-Big-Calendar, but I've run into an issue with the popup feature not functioning properly. <div className={styles.calendarContainer} style={{ height: "700px" }}> <C ...

Creating an automated HTML tag for a form input

Is there a plugin to create form inputs like the one shown above? How can I add this feature to my own website? I would like for every user input to automatically add the < br > tag. ...