What is the best way to apply a className to a component using styled-components in React?

NavigationStyles.js

import styled from 'styled-components';

export const Navigation = styled.navwidth: 100%; ;

export const MobileNavMenu = styled.ul`

    height: 80px;

    .navbar_list_class {
        font-size: 2rem;
        background-color: red;
    }   
      
    ${props => props.navbar_list_props && `  
        font-size: 2rem;
        background-color: gray;
    `}        

`;

Navigation.js import React from 'react' import {Navigation, MobileNavMenu} from "./NavigationStyles";

const NavigationComponent = () => {

return (
    <Navigation>
        {/* work no problem */}
        <MobileNavMenu navbar_list_props>Navigation Bar props</MobileNavMenu>

        {/* not work How to use..? */} 
        <MobileNavMenu className="navbar_list_class">Navigation Bar class</MobileNavMenu>
    </Navigation>
)

}

export default NavigationComponent

Answer №1

<Nav>
    <MobileNavMenu className={navbar_list_props}>Navigation Bar properties</MobileNavMenu>
</Nav>

Give it a go!

Answer №2

It appears that the styles are being defined for the children of NavMenuMobile using the class "navbar_list_class".

This should function properly with ".navbar_list_class" as well.

export const NavMenuMobile = styled.ul`
  height: 80px;

  &.navbar_list_class {
    font-size: 2rem;
    background-color: red;
  }   
`;

Answer №3

If you're looking to style children, the code below can help:

<Nav>
        {/* works without any issues */}
        <NavMenuMobile navbar_list_props>Nav Bar props</NavMenuMobile>

        {/* updated code */}
        <NavMenuMobile navbar_list_props>
            Nav Bar class
            <ul className="navbar_list_class">Nav Bar list class</ul>
        </NavMenuMobile>
</Nav>

Just keep in mind that this will apply styles to both the props and the ".navbar_list_class". You have the option to either remove the props style or add conditional styling within ".navbar_list_class".

It's worth noting that this approach may not be considered the most idiomatic or optimal solution.

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

Currently using Mongoose and Luxon to showcase the event date, however, I am encountering an issue where the displayed date is one day earlier than expected

Currently, I am working with Mongoose and Luxon to present a date chosen by the user from a form. However, there seems to be an issue where the date is being console logged as one day, but appearing on the page as the previous day. Below is my model setup ...

Tips for ensuring your jQuery events always trigger reliably: [Issues with hover callback not being fired]

My background image animation relies on the hover callback to return to its original state. However, when I quickly move the mouse over the links, the hovered state sticks. I suspect that I am moving the mouse off before the first animation completes, caus ...

How can I display an iframe element only if it exists within an object in Angular?

I'm currently exploring options to specifically display the iframe element within a block of HTML content being sent to my Angular application. While I can use a *ngIf directive in my template to check for the presence of the tag, I am unsure of how ...

Transfer external variables into the image's onload function

I am trying to retrieve image dimensions and then execute additional actions. Since the image onload function is asynchronous, I have decided to handle everything within the onload call. This is my current approach: function getMeta(url, callback) { v ...

Error: The page "..." contains an invalid "default" export. The type "..." is not recognized in Next.js

Currently, I have a functional component set up for the Signup page. My goal is to define props within this component so that I can pass the necessary values to it from another component. This is my current approach: export default function SignupPage({mod ...

Loading an HTML page using jQuery's .load() method that contains embedded JavaScript

I'm facing an issue with loading .html pages (including JavaScript) into a div element. Below is my div setup: <div class="content"></div> This is my php code: <?php if(!$_POST['page']) die("0"); $page = (int)$_POST[&a ...

How can JavaScript be used to access response header information in Devise Token Auth?

Currently, I am in the process of developing a web application using Rails as the backend API and Vue.js as the frontend library. For authentication purposes, I have integrated the devise_token_auth library. However, I am facing difficulty in retrieving th ...

Verify if the value of localStorage matches the specified value, then conceal the element

This is my second query and I'm hoping it covers everything. My knowledge of javascript is limited, which has made it difficult for me to get my code working properly. Despite trying various different approaches, I have been unable to resolve the issu ...

Using angular 7 to apply a dynamic CSS class on a span element

I want to dynamically change the CSS class of a span element in an ngx datatable based on the value. Here is my HTML code: <ngx-datatable #orderinvoice class="bootstrap" [rows]="invoiceSource" [headerHeight]="50" [footerHeight]="50" [rowHe ...

"Exploring the versatility of dynamic values in tailwindcss within a React/Next.js environment

There is a need to create a span element that moves dynamically within the day, adjusting its position based on the current time. The element should be positioned x% down of its parent div. Here is a snippet of the relevant code: const [timePercentage, se ...

Use React hooks to submit a form after updating the state

Seeking guidance on utilizing the latest react hooks. How can I update the state and then proceed to submit a form? For instance, I have a search box that relies on the typical state managed by setSearch, where upon submission, it queries data from the se ...

The issue with knockoutjs and isotope is that the new item being added causes the first element to move erratically

Currently utilizing knockoutjs along with the isotope masonry layout, incorporated with a custom binding referring to the code blog link provided here: Snippet from the View: <div id="container" class="isotope" data-bind="foreach: bills"> <d ...

Issue with npm during installation of REACT - not functioning as expected

After executing all the necessary commands on the command line, including globally installing npm with npm install -g create-react-app, as well as running npx create-react-app <myprojectname> and clearing the npm cache, I consistently encountered an ...

My website gets all wonky when I try to resize the browser

Here is a visualization of my website's ideal appearance: However, the actual display varies on different computers. After testing with browsershots.org, I noticed that my website looks messy on most browsers and even when resizing the browser window ...

What is the best way to avoid using ng-repeat for the last item being shown?

I currently have an ng-repeat loop that is dependent on an ng-if condition. Here is the specific code block: <div class="fav-prod-customised> <p ng-repeat="ingredient in product.options" ng-if="ingredient.default_quantity == 0 & ...

Maintain synchrony of the state with swiftly unfolding occurrences

I developed a custom hook to keep track of a state variable that increments based on the number of socket events received. However, when I tested by sending 10 simultaneous events, the total value of the state variable ended up being 6, 7, or 8 instead of ...

React-native: It appears that you have successfully installed react-native on a global scale

Encountering a bug with react-native when installed globally is causing an error message to appear. The issue arises when trying to run the command: $ react-native run-ios Looks like you installed react-native globally, maybe you meant react-native-cli? T ...

Aligning text vertically within an HTML <a> tag block

Calling all CSS experts! I'm struggling with aligning text to the bottom of a block element with a fixed width and height that contains a background image and a title. I've tried using display: table-cell; and vertical-align: bottom; without succ ...

Testing the update functionality of meta content in the Vue Quasar Meta component using Jest

I am currently working on unit testing the process of updating meta content for a Vue & Quasar page by utilizing the useMeta component offered by Quasar. My approach to testing this involves creating a mock Vue component called UseMetaComponent, which is ...

Troubleshooting issue with Express.json() functionality in the latest release of version 4.17

I'm currently exploring the MEAN stack and I am focused on performing CRUD operations. However, when I send data in the request body from Angular to the server, I end up receiving an empty request body. I'm unsure of where I might be making a mis ...