What is the best way to assign unique class names to components based on the current route in use?

I have a dilemma with my Search component being used on 2 different pages. I want the styling of the search component to change depending on which page it's on. Specifically, I want to use the .btn class on the Home page but switch to another class when it's on the GetWordContainer page. Is there a solution for this scenario?

Part of App.js where both page routes are defined

 <Switch>
    <Route exact path="/" render={ routeProps => 
      <Home 
        {...routeProps} />} 
      />
    <Route exact path="/definition/:word" render={routeProps => 
      <GetWordContainer 
        {...routeProps} />} 
      />
  </Switch>

Snippet from the Search component - currently styled for the Home page only

class Search extends Component {

render (){
  return (
    <div>
      <button className={styles['btn']} type="submit">search</button>
    </div>
  );
}
}

export default Search;

CSS for the Search component - style for the Home page

.btn{
    border:none;
    outline:none;
    /* display:block; */
    border-radius:50px 50px 50px 50px;
    width:200px;
    height:60px;
    font-size:30px;
    font-weight:700;
    font-family:segoe ui light;
    background-color:#CDA177;
    color:#FFFFFF;
    transition:all .5s ease-in-out;
    }

Answer №1

One way to enhance your search bar design is by creating multiple styles in the CSS file for it. By allowing your component to accept a new prop, such as theme, you can easily match it with the appropriate predefined style.

<Search theme={'style-home'} />

<Search theme={'style-counter'} />

Within your component:

<button className={styles[this.props.theme]} type="submit">search</button>

This approach allows you to build a versatile component that is not tied to specific pages within your application (e.g., getWordContainer).

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

What is the best way to trigger two functions with an 'onPress' event in React Native?

I am encountering some issues while trying to call two methods on the onPress event in the code below. How can I achieve calling one method for starting chatting and another for changing images during the onPress event? The first method is for initiating ...

Menu options are unresponsive to clicks in the dropdown

Need help fixing my dropdown menu issue. Whenever I hover over the dropdown, it disappears before I can click on any items. Here is a snippet of the code causing the problem: #navContainer { margin: 0; padding: 0; padding-top: 17px; width: 220 ...

The information retrieved through the fetch API is not displaying on connected devices

I am currently in the process of learning React and am using the Fetch API. I have successfully fetched data and displayed it on my local computer. However, when previewing it on my mobile device connected to the same network, the fetched data is not showi ...

What is the best way to convert this JavaScript iteration function into jQuery?

I recently encountered an issue with my JavaScript function that returns a list of elements with the class ".youtube", loops through them, and calls another function. The JavaScript logic is flawless, but I wanted to convert it into jQuery for better reada ...

Tips for maintaining node selection when clicking on a pane in React flow

Currently, I am working on a website where users can select multiple nodes to perform specific operations. I want to ensure that all selected nodes are visually highlighted with a colored border. However, when I click on the pane after selecting nodes, the ...

ngAnimate removeClass behaving unexpectedly

Recently, I've been delving into the ngAnimate module for AngularJS version 1.2.14 When employing $animate.addClass, everything seems to function as expected with the ng-animate, -add, and -add-active classes seamlessly added. However, my struggle a ...

The functionality of onClick or onChange seems to be malfunctioning in the preline user interface select component

I recently integrated the preline UI library into my React project to enhance the design of my website. However, I encountered an issue where using the "select" element with the data-hs-select attribute as suggested by preline UI seemed to cause problems w ...

Leveraging material-ui themes in conjunction with react-router

Currently working on an app that utilizes material-ui along with react-router and connected-react-router. I'm facing an issue while trying to switch to the dark version of the default theme. It seems like the ThemeProvider is not passing the props dow ...

Creating layers of object declarations

Looking for assistance on the code snippet below. type Item = { id: number; size: number; } type Example = { name: string; items: [ Item ]; } var obj: Example = { name: "test", items: [ { i ...

What is the best way to showcase information retrieved using the getDocs function from Firebase Firestore?

Hello! I am currently exploring the world of Firestore and facing a challenge. My goal is to retrieve a data object from Firestore, set it as state, and then display it on my application: Below are the imports that I have utilized for this task (please ig ...

"Enhance your editing experience with React's dynamic draft editor featuring real-time

I am facing an issue with a rich text editor that is used to submit a description. While updating fields on the detailsPage using an editorToggle, I noticed that the textEditor does not transfer the submitted description as expected when displayed with Rea ...

Leveraging css modules in combination with the Extract Text Plugin

Having an issue with my Webpack 2 build in production mode when using the css modules option in css-loader with extract-text-webpack-plugin. The classes are generated correctly on HTML elements, but the extracted CSS file lacks the identifiers. I have fol ...

When adjusting the size of the browser window, the div on my web page shifts to the bottom, creating a large empty space at

I have encountered an issue where, when I resize the browser window, my div moves to the bottom and leaves a large space at the top. I would like the div to remain in the center of the page, even if I resize the window to be smaller than the size of the ...

Having trouble resolving '@material-ui/lab/AdapterDateFns' for Material UI Lab's date picker

Encountering resolution issues with '@material-ui/lab/AdapterDateFns' Struggling to resolve '@material-ui/lab/DateTimePicker' Unable to resolve '@material-ui/lab/LocalizationProvider' Despite having installed @material-ui/l ...

Tips on loading content with setContent in Tiptap while using React

They have provided thorough information on content and commands in general. However, I've been searching everywhere using ctrl+F to find where "commands" should be inserted in the code. My goal is to load HTML that I previously exported with the Tipta ...

Is there a way to identify the accurate or incorrect array element and modify the component color accordingly?

Upon reviewing the question alternatives, I encountered a problem where clicking on one of the buttons correctly indicated whether it was the correct or incorrect answer by changing its color. However, the issue is that all buttons are being affected by th ...

Sending a property to a dynamically created child component once the main component has finished mounting

In my project, I have a component that acts as a container for a <canvas>. Other components in the project take a canvas context as a prop and are able to manipulate it in various ways. Here is an example: class App extends React.Component { ctx: ...

Error encountered when attempting to listen on port 443: EADDRINUSE

My React application requires an HTTPS connection, so I have to run it on port 443. Regardless of the port I use, I keep encountering the following error: 0|server | at Module.load (node:internal/modules/cjs/loader:981:32) 0|server | at Functi ...

"Utilize the OpenWeather API to dynamically adjust the time based on the city entered in the search

Currently, I am using the openweatherapi to develop a weather application in reactjs just for fun. While I have successfully implemented displaying the current time, I am facing a challenge on how to dynamically update it based on the city searched. Any su ...

Implementing file upload feature with Express JS and React JS

I am looking to implement a unique file upload system in my full stack application. Specifically, I want to create a process where a single file uploaded from a react frontend is divided into multiple chunks on the client side and then sent to an express s ...