Should conditions be applied inside SX Props in a Material UI Component?

My goal is to dynamically change the UI of the Navigation Component based on the current pathname in history. I have created a function named UI that calls another function, BoxPadding, based on the location. The BoxPadding function takes a parameter for padding and returns some Typography elements. Within the Typography components, I use props to set the padding value accordingly. For example, when the Blog component is displayed, the padding should be 0, and for other components, it should be 10. However, I am experiencing issues and not getting the expected result. Is it advisable to use props within SX props?

import * as React from 'react';
import NavBar from './../NavBar/NavBar';
import TopHeader from './../Header/TopHeader';
import { Typography } from '@mui/material';
import { createTheme } from '@mui/material';
import { Box } from '@mui/material';
import { styled } from '@mui/system';
import { useHistory } from 'react-router-dom';

import './Nav.css'
const theme = createTheme();

theme.typography.h3 = {
  fontSize: '1.5rem',
  '@media (min-width:600px)': {
    fontSize: '1.2rem',
  },
  [theme.breakpoints.up('md')]: {
    fontSize: '2rem',
  },

};

export default function Nav({ img, text, textcolor }) {

  const history = useHistory();
  const pathName = history.location.pathname

  const MyComponent = styled('div')({
    backgroundImage: `url(${img})`,
    height: "100vh",
    backgroundPosition: 'center',
    backgroundRepeat: 'no-repeat',
    backgroundSize: 'cover',
    padding: '10px',
    margin: '0px',
  })


  const BoxPadding = (padding) => {
      return (
        <>
          <Typography theme={theme} sx={{ fontFamily: 'Poppins', textAlign: 'center', p: { lg: `${padding}`, xs: 1 }, height: "100%" }} component="div">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
            when an unknown printer took a galley of type and scrambled it to make a type specimen book.
          </Typography>
          <Typography theme={theme} sx={{ fontFamily: 'Poppins', textAlign: 'center', color: 'orange', fontWeight: 'bold', marginTop: { lg: '10px', xs: '0px' }, }} variant="h5">
            Lets go..
          </Typography>
        </>
      )
    }
  

  const UI = () =>{
    if(pathName==='/Blog'){
      BoxPadding(0)
      console.log("10")
    }
    else{
      BoxPadding(10)
      console.log("10")
    }
  }
  return (
    <>
      <MyComponent height="">
        <TopHeader></TopHeader>
        <NavBar></NavBar>
        <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', p: { lg: 4, xs: 0 }, width: { lg: "50%", xs: '100%' }, mx: 'auto', color: { xs: `${textcolor}` } }}>
          <Typography theme={theme} sx={{ fontFamily: 'Poppins' }} variant="h3" textAlign="Center">
            {text}
          </Typography>
          {UI()}
          


        </Box>
      </MyComponent>
    </>
  )




}

Answer №1

To enhance your code, consider using useLocation instead of useHistory:

let currentLocation = useLocation();
const urlPath = currentLocation.pathname
console.log(urlPath) // /Products/

This change allows you to easily identify the current URL.

Next, streamline the if-else statement:

if(urlPath === '/Products/'){
      adjustPadding(0)
      console.log("0")
    }
    else{
      adjustPadding(10)
      console.log("10")
    }

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

Tips for adjusting the vertical position of an image within a bootstrap column by a small amount

Apologies in advance if this question has already been addressed, and I am struggling to adapt it to my specific scenario. My objective is to adjust the positioning of the two images shown in the screenshot example below so that they align with the grey b ...

What is the best method for efficiently concatenating files from different directories in Grunt?

Apologies for the awkward question title, if anyone can suggest a better way to phrase it, I'm open to changing it immediately. In the process of developing an app using Angular and RequireJS with a focus on performance optimization, dependencies, an ...

When you hover, there is no writing cursor in sight

I'm looking for a way to display a label on an input field and have a writing cursor show up when hovering over the label. I am not interested in using a placeholder label. Do you have any simple solutions for this? See the code snippet below: JSFiddl ...

Clear the text in a textarea after submitting the form

I am facing an issue with a comment box (textarea) inside a dialog. After successfully saving the comment, I want to clear the content of the textarea and close the dialog box. Currently, the dialog box closes, but the content remains in the textarea. < ...

Font distortion caused by Slick slider appears in an unexpected location in Chrome

Slick slider causing font issue in a different location specifically on Chrome Encountering a very peculiar situation where the font in a 3-column block with red titles within my slick slider appears slightly darker while transitioning to the next/previou ...

What is the process for connecting controls to Canvas sprites?

Any input is EXTREMELY helpful! To put it shortly, I'm in need of assistance with utilizing HTML5/CSS3 buttons to manage sprite animations on my canvas. These buttons are responsible for controlling the direction and speed of the sprites independentl ...

Contrasting $window.location.reload() and $route.reload() functions in AngularJS

Could someone clarify the distinction between $window.location.reload() and $route.reload() in Angular.js? Although I have implemented both methods, I have noticed they achieve similar outcomes. Would someone be able to provide an explanation of the vari ...

What is the best way to generate a live map with constantly updating markers?

Is it possible for me to learn how to develop a live map similar to the one on this site: www.lightningmaps.org? It's fascinating to watch new markers pop up every few seconds. I'm interested in building a real-time map that can track IP locatio ...

Steps for building a dynamic layout using bootstrap 4

I've been working on creating a responsive layout similar to the image using Bootstrap 4, but I'm encountering some issues. Specifically, I'm having trouble making the sidebar and bottom bar fixed, as well as adjusting the size of the bottom ...

A guide on utilizing multer-sftp for downloading files

I've been working on this code, but after searching online I still haven't found a way to download a file from the remote server. I can successfully upload files to the server, but downloading them is posing a challenge. var storage = sftpStorag ...

What is the rationale behind using :: before display: inline-block in Angular Material MDC's mat-mdc-form-field-error-wrapper, causing substantial padding?

I recently made the switch from Angular Material to Angular Material MDC in preparation for upgrading to Angular 17 from version 15. However, I've noticed that some styles are now broken. One issue I'm facing is a significant padding between the ...

Having trouble accessing the desired API as the Next.js Dynamic API Page keeps returning "local..../undefined/api/......"

Within my React components, I have implemented a function called "statusHandler" that makes a fetch call to "api/orders/ + ID" where ID is a unique item identifier. My setup involves using Next.js and pages to access API routes. An error I encountered rea ...

Discover and eliminate the style attribute through a click action

I've been struggling to find a solution to remove the style attribute from a specific tr tag within a table when it is clicked. I've tried several lines of code but none seem to work. Here's the link to the fiddle for reference: http://jsfi ...

jQuery Mobile dual range slider functioning but experiencing some glitches

I successfully created a dual range slider by stacking two sliders on top of each other using the jQuery Mobile framework. In addition, I have implemented JavaScript to ensure that the left thumb does not exceed the right one. However, I have encountered ...

ng-disabled with function that activates on change

I am attempting to create a submit validation button that will only enable when all fields have been entered correctly. Due to the complexity of the validation process, I am unable to rely solely on formName.$invalid and need to write a custom function for ...

Execute the function that has been passed through a data attribute

I am attempting to execute a function using its name, which is passed through a data attribute in the HTML. I have made an attempt with the code below: HTML: <div class="generic-select" data-help-on-shown="genericFunction" > </div> ...

The selected option on the Select dropdown does not seem to be updating the effect as expected

I made a change to the options but useEffect is not updating the input. Can you please guide me on where I might have made a mistake? Initially, I used useEffect to set the currency and then used mapping to access getCurrency and add it as an option in t ...

Creative Wrapping with EaselJS

Most canvas frameworks have a built-in feature for controlling word wrapping using maxWidth and maxHeight parameters. While setting the maxWidth in EaselJS is straightforward, is it possible to efficiently set a maxHeight for text as well? ...

Creating a buffered transformation stream in practice

In my current project, I am exploring the use of the latest Node.js streams API to create a stream that buffers a specific amount of data. This buffer should be automatically flushed when the stream is piped to another stream or when it emits `readable` ev ...

Creating a scrollable div with a fixed background using HTML

Attempting to create a full-screen image background with a scrollable div in its center, I crafted the following code: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Bio</title> <link href="../css/layout ...