Customize the style based on the state using styled components

I am currently working with a function component that looks like this:

const Navbar = ({setNav, nav}) => {
  const [justify, setJustify] = useState('space-around')
  //get localStorage
  const user = JSON.parse(localStorage.getItem('user'));


  //change state of nav to display user details
  if(user){
    setNav(true)
  }
  console.log(nav)



  return (
    <Nav>
      <Img src={logo} alt='groupomania' />
      {nav  ? <UserDetail setNav={setNav}/> : ''}
    </Nav>
  );
};

My goal is to dynamically adjust the justify-content styling based on the state. However, my attempts so far have not been successful.

This is what I have tried:

const Nav = styled.nav`
  position: sticky;
  background: #eeeeee;
  min-height: 10vh;
  display: flex;
  flex-direction: row;
  justify-content: ${nav  ? 'space-between' : 'space-around'};
  align-items: center;
  border-bottom: solid 1px #e5e5e5;
  padding: 1rem 10rem;
  top: 0px;
`

Answer №1

Have you considered placing that clause directly within the line of code?

<Header style={{ 'align-items': header ? 'center' : 'flex-start' }}>
  ... ...
</Header>

Answer №2

Although the answer provided by Bubai is effective, I personally prefer not to use inline styling.

After experimenting with different options, I found a more suitable solution:

 <Nav>
   <Img src={logo} alt='groupomania' />
   {nav  ? <UserDetail setNav={setNav} nav={nav} /> : ''}
</Nav>

I have included the nav={nav} prop in the component. Now I can utilize the following code:

const Nav = styled.nav`
  position: sticky;
  background: #eeeeee;
  min-height: 10vh;
  display: flex;
  flex-direction: row;
  justify-content: ${props => props.nav  ? 'space-between' : 'space-around'};
  align-items: center;
  border-bottom: solid 1px #e5e5e5;
  padding: 1rem 10rem;
  top: 0px;
`

I found this resource incredibly useful https://styled-components.com/docs/advanced

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

Playing only audio and no video in an Android WebView using HTML5

I am currently facing a challenge with a webpage that includes an html5 video and css3 animations. While the web page functions perfectly on an android device's browser, I am experiencing laggy, glitchy, and jumpy animations when using hardware accele ...

Adding a closing button to a tab with Material UI: A step-by-step guide

In the process of building dynamic tabs with ReactJS and Material UI, I am curious about how to add a practical close button directly onto each tab. By "this," I mean having an icon like this: https://i.stack.imgur.com/FdTrH.png Also, is there a way to h ...

A guide on showcasing the chosen item in a row using Material UI

I am currently working on a dropdown component that allows users to select their desired language. The goal is to display the selected language's image and text in a row, but I'm facing an issue where the selected item is displayed vertically ins ...

Include an additional Div tag in the existing row

I've been attempting to include an additional div, but it consistently appears as the second row.. I want all of them to be on the same row and aligned with each other. Here is the HTML code: <div class="content-grids"> <div clas ...

InvalidSelectorError: The specified selector is not valid //button[contains(., 'buttonText')] while running JavaScript code

Here's an example of HTML code that I am working with: <button id="toolbar-item-17-update-id" type="submit" name="action" value="update" class="button-action-update btn btn-secondary"> Ed ...

Can cells be divided in a Material UI table?

Is there a way to split a cell in a Material UI table?I am aware that I can create a component to achieve this, but I'm wondering if there is another approach that I may not be aware of. Splitting a cell means having two values separated by a line wit ...

Adding additional images to the left side of the slide

My goal is to display multiple images in two rows. The alignment works well for up to 9 images, but beyond that, the additional images appear on a third row instead of staying within the two rows. I want to ensure they are contained within 2 rows only. How ...

When viewed on a mobile device, the entire HTML document is resized to occupy less than half of the

Whenever I adjust the size of my webpage on different devices or mobile phones, I notice that the <div> tag appears to be only half (or even less) the width of the page. This gap seems to increase as the window size decreases. Refer to the screenshot ...

Retrieve the id for the chosen user name within a function that contains an array of objects

const userList = [ {name:"jonh" ,id:EAD1234}, {name:"peter" ,id:EAD1235}, {name:"matt" ,id:EAD1236}, {name:"henry" ,id:EAD1237}, ] In the array above, there are various users with their respective IDs. The goal is t ...

Using OAuth2 for Single Sign-On and Redirecting to a React Single Page Application

I am currently working on a React SPA for a client who has implemented OAuth2 for single sign-on with their own login page. Once the user logs in, they are redirected back to my application. I am looking for a way to integrate my app with OAuth2 to check i ...

Encountering an issue while trying to establish a React application

C:\Users\KARTHIKA\React>npx create-react-app part2 npx: installed 67 in 6.481s Creating a new React app in C:\Users\KARTHIKA\React\part2. Installing packages. This might take a couple of minutes. Installing react, re ...

Adjusting the minimum and maximum values for a number input in ReactJS with the final-form-material-ui package

Currently, I am utilizing final-form along with final-form-material-ui I have been attempting to set minimum and maximum values for number inputs. I have already tested the following: InputProps={{ inputProps: { min: 0, max: 10 } }} Unfortunately, this a ...

How can I utilize a custom function to modify CSS properties in styled-components?

I am working with styled components and need to set the transform property based on certain conditions: If condition 1 is true, set the value to x. If condition 2 is true, set the value to y. If neither condition is true, set the value to null. Despite ...

How to responsively position and scale a background image for a full-width div

Here is the situation: I have an SVG with dimensions of 1920*1920 pixels () This is what I require: I intend to use it as a background-image for a div that spans the full width of the screen. The background image for the div must be responsive. An essent ...

Changing a single state in React results in the modification of both states simultaneously

Whenever I attempt to modify one state, I find that another state is inexplicably changing as well. I've scoured my code for the issue but can't seem to pinpoint it. What steps should I take next? Here's the snippet of code in question: impo ...

React Material UI unselect

I have been exploring a MUI select field implementation using this example as a guide. While I was able to make the code work, there are a few issues that I encountered. One of them is the inability to deselect a value once it has been selected. Additional ...

Attempting to utilize Flexbox to populate vacant areas

https://i.stack.imgur.com/BhPU0.png Can the yellow square smoothly transition to the empty grey square and beyond in this layout setup? Each flex item represents a component that can utilize either 50% or 100% of the container width, information only know ...

How to send an image file to Amazon S3 using React JS

I have successfully implemented code that can upload several files to an S3 bucket. However, there seems to be an issue with the uploaded image files as they appear corrupted and cannot be opened. I am looking for a way to upload these files as images or ...

What is the method for moving one div above or below another div using the scroll bar?

Here's the scenario I'm facing: I have rows with buttons that, when clicked, reveal a set of options. The challenge is that depending on where the row is located on the page, the settings need to open either above or below the button. When the b ...

Retrieve information from child components and populate form fields

Currently, I am working on creating a dynamic form that utilizes a sub component to display input fields because creating them statically would exceed a limit. I pass the states for the form I created along with some data and the change form function. Howe ...