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

Having issues with the horizontal list layout

I am having trouble implementing Bootstrap horizontal lists on my website. How can I resolve this issue? Desired outcome: https://i.sstatic.net/zzBFi.png Current situation: https://i.sstatic.net/cfoZN.png Below is the snippet of CSS code in question ...

The syntax for importing JSON in JavaScript ES6 is incredibly straightforward and

Whenever I attempt to write my code following the ES6 standard and try to import a .json file, it ends up failing on me. import JsonT from "../../Data/t.json" //not functioning as expected var JsonT = require('../../Data/t.json'); //works fine ...

React encountering a 400 Bad Request Error with Axios

I've gone through all the posts about Axios 400 bad request, but I still can't find a solution. In my useEffect function, I first fetch data from my API and later on, depending on certain conditions, I may need to make a POST request back to the ...

Enhance the functionality of Immutable.js field by integrating a custom interface in Typescript

Imagine a scenario where the property name is field, essentially an immutable object. This means that methods like field.get('') and other immutable operations are available for use. Nevertheless, I have my own interface for this field which may ...

What is the reason for translate3d(…) causing a scrollbar to appear on iframes?

Is there a way to hide the tiny, fixed scrollbar that appears at the bottom of an <iframe> with overflow-x: scroll, even when there is no content to scroll, while keeping the transform: translate3d(0px, 0px, 0px) style set? I am unable to modify the ...

Hide specific content while displaying a certain element

Creating three buttons, each of which hides all content divs and displays a specific one when clicked. For instance, clicking the second button will only show the content from the second div. function toggleContent(id) { var elements = document.getEl ...

Establish proxied EventSource (SSE) connections via NodeJS to a backend server running on localhost

Encountering a problem with EventSource connections when using node-http-proxy v1.18.1. Everything works fine during development with create-react-app and proxy:, but once deployed to production, the connection fails and displays the following browser (chr ...

Step-by-step guide on how to display a single button within the 'Component' section in React

I recently created a button within a .ts file located in the 'components' folder using the React framework. I am curious to know the fastest method to preview this button that I have designed. Since I am still learning, it wouldn't be feasi ...

Is there a way to export a variable that has been declared within a function component in React Js?

I am currently developing a React app and I need to export the RoomPricelist1 & FacilityPricelist1 variables. I have assigned values to these variables within a function component but when I try to import them into another function component, they are sh ...

Is AnimatePresence effectively used for page transitions on exit in Next JS 13?

I've been attempting to incorporate exit animations using framer-motion in a Next JS 13 project with the new app router. AnimatePresence appears to function properly, but not for exit animations. It seems like the mode="wait" attribute is e ...

Jest is having difficulty locating a module while working with Next.js, resulting in

I am encountering some difficulties trying to make jest work in my nextjs application. Whenever I use the script "jest", the execution fails and I get the following result: FAIL __tests__/index.test.tsx ● Test suite failed to run ...

Reducing Image Size for Logo Placement in Menu Bar

Hello all, I am a newcomer to the world of web coding. Please bear with me if I ask something that may seem silly or trivial. I recently created a menu bar at the top of my webpage. Below that, there is a Div element containing an image. My goal is to make ...

Error in React JS: The split method cannot be applied on selectedWord

Currently, I am developing a Hangman game in React JS and encountered an error message that reads "TypeError: selectedWord.split is not a function". The section of code causing the issue is shown below: const Word = (selectedWord, correctLetters) => { ...

I am trying to center align this image, but for some reason, it's not cooperating

Attempting to center the image using margin-left: auto and margin-right: auto properties in the code snippet above has proven unsuccessful. The image is not aligning as desired. What could be causing this issue with the code? Are there any other techniq ...

Utilize CSS to showcase the full-size version of a clicked thumbnail

I am working on a web page that features three thumbnails displayed on the side. When one of these thumbnails is clicked, the full-size image should appear in the center of the page with accompanying text below it. Additionally, I have already implemented ...

Switch between using the useState hook by toggling it with the MUI Switch

Looking to implement a custom Dark Mode feature for a specific element on my create-react-app website using MUI. I have successfully implemented the Switch to change the state on toggle, but I am having trouble figuring out how to toggle it back and fort ...

Having trouble locating the nivoslider IE8 jQuery bug, can't seem to track it

I am encountering an issue with the nivoslider script in IE8 and I am having trouble identifying what is causing it. The nivoslider works perfectly fine in all other browsers except for IE8. Any help or guidance on this matter would be greatly appreciated ...

What distinguishes between using ul#test and #test ul in CSS?

Could someone help clarify the distinction between these two types of CSS declarations: ul#test { } #test ul { } Despite my searching, I am unable to pinpoint the difference, but they exhibit different behaviors when implemented on a test page. To me, i ...

What steps should be taken to fix the error "Warning: Encountered multiple children with the same key" in React.js?

I'm having trouble fetching and displaying data from an API. Whenever I attempt to show the data, I encounter the following error message: Alert: Found two children using the same key, [object Object]. Keys must be unique so that components can pro ...

No results appearing in the output section

While developing a website using React, I encountered an error that said useState is defined but never used in the navbar component. To address this, I made changes to my ESLint configuration in the package.json file: "rules": { "eqeqe ...