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

My PHP file is throwing an error that involves converting an array to a string and an uncaught PDOException with the SQLSTATE[HY093] code

I'm encountering an issue with this file. Here are the error messages: Warning: Array to string conversion in C:\xampp\htdocs\backhaul-dispatcher\login\process.php on line 46. Fatal error: Uncaught PDOException: SQLSTATE[HY09 ...

In a perplexing turn of events, the Dojo dtl tag logic

Dojo dtl (Django Template Language) is being used to render a widget by passing an array with multiple objects. The iteration over the objects and their subarrays is functioning properly, but there seems to be an issue with applying an 'if' condi ...

Here's a way to run JavaScript code from a <script> tag included in an AJAX response

Currently, I am making a jQuery GET request in this format: $.get($(this).attr("href"), $(this).serialize(), null, "script"); I'm expecting the response to be enclosed in script tags. I know that the browser won't run the response if it contai ...

Indication of a blank tab being displayed

I'm struggling to get my Angular directives working in my project. I've tried implementing a basic one, but for some reason it's not showing anything on the screen. Can anyone help me troubleshoot this issue? Here is my JS code: angular ...

Issue with material table not showing data

Problem I've been working on integrating a material design table into my project, but I'm running into an issue where the data isn't showing up. I followed the example provided here but all I see is a single vertical line on the page: Upon ...

Enhance the clarity of content within an IFrame by sharpening the focus on

I recently developed an iframe to open a chat site I built using React.js and Tailwind. The iframe is loaded dynamically on the website through javascript. However, I noticed that when I click on the input field inside the iframe, the content appears blurr ...

Unable to keep button contained within form's card design

Currently enhancing my Bootstrap skills and seeking assistance with a card and form alignment issue. Struggling to properly place a form within a card. Any suggestions or insights on resolving this? <div class="row row-content col-sm-8"> &l ...

Is it possible to adjust the color of this AnchorLink as I scroll down?

Currently struggling to update the color of a logo as I scroll. While the navigation bar successfully changes colors, the logo remains stagnant. Here is the excerpt from my existing code: navigation.js return ( <Nav {...this.props} scrolled={this ...

Display the input text line by line

How can I achieve the desired output for this input parameter? displayText("you and me"); expected output: ["you and me", "you and", "and me", "you", "and", "me"] I have attempted ...

Access a JSON response within an HTML/JavaScript document

Can the scenario below be achieved? Here is the ajax response I received: HTML <body> <input type="text"></input> <div id="trydiv"></div> </body> JS $.ajax({ type: "POST", url: "json.php", ...

Experiencing a hiccup while attempting to query the Twitter API using Node.js

I am a beginner exploring the world of node.js, but I keep encountering a perplexing "write after end" error. Despite searching for solutions online, none seem to address my specific issue. My current project involves querying the Twitter API. req.on(&apo ...

React fullpage.js causing z-index stacking problems

Take a look at the demo here: I'm having trouble getting the 'more info' modal to display above all other elements on the screen. Here's the desired stacking order, with the highest stacked element listed first: modal nav open header ...

Async reaction in MobX is a powerful tool for handling

Hey there, I am currently utilizing MobX in a store and faced with the need for an asynchronous reaction to occur when a computed value changes: class Store { @observable user; @observable something; @computed get firstParam () { ret ...

JQuery GET brings back unnecessary HTML content

Currently utilizing a PHP cart class and implementing some jQuery to dynamically update a div when users add products. The issue I'm encountering is that upon adding a product, the list of products on the HTML page gets duplicated (see screenshot) ev ...

Seeking to develop a pair of functions for submitting data via my website's form

I need to pass form data to both Docusign and Zapier with just one button click using JavaScript. When the Submit button is pressed, I want the data to be sent to Zapier without opening a success page and then redirect to the Docusign page with all the in ...

Searching for and replacing anchor tag links within a td element can be achieved using PHP

I am currently customizing my WordPress website and I need to update the URL (product link) of the "product-image" on the "cart" page. I have the following dynamic code: <td class="product-name" data-title="Product"> <a href=&q ...

Guide to simultaneously displaying two modals in react.js with either MUi or tailwindcss

Can anyone help me implement a modal with the same functionality as the share feature on Google docs or Google drive? I am looking for guidance on how to achieve this and if there are any examples available on CodePen or similar code sharing websites. htt ...

What is the mechanism through which the subtraction operator initiates the conversion of an array to a

Here are a couple of examples showcasing my code. Let's start with the first one: console.log([4] + 10); //"410" It is commonly known that the addition operator can only work with numbers and strings. Therefore, in this case, [4] needs to b ...

What is the best way to find out the height of a row?

I'm curious to understand why setting a height value for the first flex-item in the example below results in an increase in the height of the first row. It would be helpful to determine how to calculate the height of a row, especially when the height ...

Select checkboxes by clicking a button that matches the beginning of a string in JavaScript

I have a form with a list of users and checkboxes below their names. Each user has a button that should select all checkboxes assigned to them. Below is the code for the dynamically created buttons and checkboxes. The included function takes the form name ...