Is it possible to style a React component based on the rendering of another component?

I have a component called Search that I want to be displayed differently depending on which page is being rendered. On the homepage, I want it to appear at the bottom of the page, but on all other pages, I want it to be at the top.

Currently, my app.js looks like this:

const App = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route path='/' component={Home} />
        <Route path='/about' component={About} />
        <Route path='/work' component={Work} />
        <Route path='/contact' component={Contact} />
      </Switch>
    </BrowserRouter>
  )
}

Inside a page component, like Contact for example:

const Contact = () => {
    return (
      <div>
        <Search />
        Contact
      </div>
    )
}

However, this means I have to manually add the Search component to each page component and decide its placement every time.

Is there a way I can modify my app.js like this:

const App = () => {
  return (
    <BrowserRouter>
      <Search />
      <Switch>
        <Route path='/' component={Home} />
        <Route path='/about' component={About} />
        <Route path='/work' component={Work} />
        <Route path='/contact' component={Contact} />
      </Switch>
    </BrowserRouter>
  )
}

And then dynamically style the Search component based on which page is being rendered, so it appears in the correct position.

Thank you!

Answer №1

To enhance the Search component, I suggest including a prop called `className` and implementing an if statement. For instance:

<Search className={location === '/' ? 'top' : 'bottom'} />

Answer №2

Utilizing the useLocation() hook from React Router enables you to easily identify the current page you are on.

const ContactPage = () => {
  const currentLocation = useLocation();

  const contactStyles = currentLocation === "something" ? {...topStyles} : {...downStyles};

  return (
    <div>
      <Search style={contactStyles} />
      Contact Page
    </div>
  )
}

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

Creating a persistent footer in a modal: A step-by-step guide

I'm currently working on a react-modal that slides in from the bottom of the screen with an animated effect. The challenge I am facing is getting the footer of the modal to stay fixed at the bottom of the browser window. Despite using the standard CSS ...

Automatically changing the color of the navigation bar text

I am experiencing an issue with the navigation bar on my webpage. Currently, it is styled with white text against a dark background color using the following CSS code snippet: a{ color: white; text-decoration:none; font-weight:bold; font-s ...

I'm having trouble with my "alert()" function in Vue.js

I am new to using Vue and I am attempting to trigger an alert function when a button is clicked. However, I keep encountering the error message Uncaught ReferenceError: addTask is not defined. Below are the codes I have written: <template> ...

What is the process of incorporating a code editor into Material UI design?

Despite trying numerous popular code editors from npm, I have encountered an issue where none of them seem to be displaying monospace fonts correctly. Even after attempting solutions like ThemeProvider and inline styles, the problem persists. What's i ...

To properly render JSX elements in ReactJS, make sure to enclose adjacent elements within a wrapping tag. If you prefer to use a

Hey, I just started learning React and decided to create a blog. The blog elements are stored in an array and I'm using a map function to display the blog posts. However, when I add something to the map function, I encountered this error: Adjacent JSX ...

Creating a scrolling background effect using HTML and CSS: ``Background Parallax

I'm trying to keep the background of my HTML document fixed in the upper left corner, so that when a user scrolls through the page, they only see parts of it. Here's the code I'm using: <body style="background-image: url(background.png) ...

Interactive calendar feature with a popup that appears when hovering over an event

I am looking to create a popup on hover with full calendar functionality, similar to the one seen at this link. I have attempted using full calendar with qtip, but I was unable to achieve a clickable popup as it disappears when the mouse moves away. Here ...

Unable to assign a value to a property within a JavaScript object

I'm attempting to configure settings for a JavaScript object (my assumption is that it's not a plain JS Object, but possibly an instance of a specific class, though I haven't been able to identify the class). https://i.sstatic.net/xsUiJ.png ...

What could be causing the TailWind CSS Toggle to malfunction on my local server?

While working on designing a sidebar for a ToDo page using Tailwind CSS, I encountered an issue with implementing a toggle button for switching between dark mode and light mode. In order to achieve this functionality, I borrowed the toggling code snippet f ...

Having trouble getting the Babel plugin transform-remove-console to function properly with the Vue CLI 4 and @vue/cli-plugin-babel/preset?

When you create a VueJS project using Vue CLI 4, Babel is configured with a useful preset in babel.config.js: module.exports = { presets: [ '@vue/cli-plugin-babel/preset', ], }; I am attempting to use babel-plugin-transform-remove-conso ...

Querying a collection with a bulk request using Mongoose Cursor

My current challenge involves working with rxJS and handling bulk HTTP requests from a database containing over 1 million documents. The code I have is relatively simple. I am pushing all the documents from the collection into an array called "allPlayers" ...

Tips on avoiding the repetition of jQuery functions in AJAX responses and ensuring the effectiveness of jQuery features

My HTML form initially contains only one <div>. I am using an AJAX function to append more <div> elements dynamically. However, the JavaScript functionality that works on the static content upon page load does not work for the dynamically added ...

Tips for inserting a footer at the bottom of every page during the conversion process from HTML to PDF

Could use some assistance with converting HTML into a PDF report. In particular, I want the footer to always appear at the bottom of the last page, even if there is minimal content on that page. Any suggestions? I've been utilizing the wkhtmltopdf to ...

Breaking down the color code system in React Material

I have been incorporating the react-material and MuiThemeProvider component for utilizing themes. Below is the code snippet that I replicated from the example provided on the website: const theme = createMuiTheme({ palette: { primary: purple, // Pu ...

storing information in localStorage using react-big-calendar

Incorporating react-big-calendar into my project, I encountered a problem where the events in the calendar would disappear upon page refresh despite saving them in localStorage. I had planned to store the events using localStorage and retrieve them later, ...

Update the data-value parameter dynamically after a successful Ajax request without utilizing the element's

I have a bunch of different buttons to switch the status of various projects: <div class="btn-group btn-toggle project_status" data-project-id="1" data-form="project_status" data-value="1"> <button class="btn btn-default active">ACTIVE</ ...

Creating dynamic form groups that allow for the addition and removal of forms while assigning unique identifiers and names to each input field

I am currently immersed in the development of a sophisticated CMS system. My main objective is to dynamically add and remove form inputs using JavaScript upon clicking a button, with the ultimate goal of submitting the data into a database via PHP script. ...

Custom Map Typescript Interface

Here is the structure of my interface: export interface IMyMap { [index: string]: RefObject<HTMLElement>; } This interface was created following the guidelines in the documentation: Indexable Types I am trying to implement this interface in a Re ...

Selecting a date in a pop-up

In my PHP application, I have incorporated a date selection feature within a modal dialog. However, when clicking the control, the calendar appears in the left corner of the page and remains visible even after selecting a date. Additionally, clicking elsew ...

Instructions for creating a straight border on the right side of an icon

Within my project, I have incorporated material-ui and included icons in the header. The first two icons require a border-right style to be added. However, the issue I am facing is that the border appears rounded, as shown in the image below, whereas I nee ...