How to toggle 'className' dynamically in react.js?How do JavaScript closures work?How to horizontally center a <div>?How do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do I redirect to another webpage?How to disable text selection highlighting?How do I include a JavaScript file in another JavaScript file?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?How do I return the response from an asynchronous call?

Creating a character, is Noble a class or a background?

More output neurons than labels?

License validity of unreleased project

What happens if there is no space for entry stamp in the passport for US visa?

When did the US colonies/states stop making their own currencies?

Why are road bikes (not time trial bikes) used in many triathlons?

Why did Spider-Man take a detour to Dorset?

Does the Intel 8085 CPU use real memory addresses?

Can you perfectly wrap a cube with this blocky shape?

How to ask my office to remove the pride decorations without appearing anti-LGBTQ?

How can I find what program is preventing my Mac from going to sleep?

Why does FFmpeg choose 10+20+20 ms instead of an even 16 ms for 60 fps GIF images?

Will a contempt of congress lawsuit actually reach the merits?

Is this artwork (used in a video game) real?

Advice for paying off student loans and auto loans now that I have my first 'real' job

Is there a standard way of referencing line numbers in a draft?

Why is Katakana not pronounced Katagana?

Data Filters and Measures Error for Unique Opens

A scene of Jimmy diversity

Using two linked programs, output ordinal numbers up to n

How to say no to more work as a PhD student so I can graduate

When does Fisher's "go get more data" approach make sense?

Fantasy Story About A Boy And Girl That Enter A Fantasy World Pre-1994

Animal Shelter Management C++



How to toggle 'className' dynamically in react.js?


How do JavaScript closures work?How to horizontally center a <div>?How do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do I redirect to another webpage?How to disable text selection highlighting?How do I include a JavaScript file in another JavaScript file?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?How do I return the response from an asynchronous call?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I want to set the active class dynamically in react.js but it's not working!
I'm using the setState() method to change the selected item.



this line of code not work .
className=selectedCategoryId === item.id ? 'active' : ''



I think the setState() function does not work correctly...



const open, selectedProduct, productCategory, filteredProducts, selectedCategoryId = this.state;
const categoryItems = productCategory.map((item) =>
<a key=item.id
onClick=() => this.handleFilter(item.id)
className=selectedCategoryId === item.id ? 'active' : ''
// className=()=>this.isActive(item.id)
className="pointer"
>item.value</a>
);


this does not change the class:



handleFilter = (id) => 
const filteredItem = this.state.productList.filter(x => x.categoryId == id);
this.setState(filteredProducts: filteredItem, selectedCategoryId: id);



but this change the className correctly when select I all tags:



handleRemoveFilter = () => 
this.setState(filteredProducts: this.state.productList, selectedCategoryId: 0);

//-------------------------------
<div className="tag-list">
<a onClick=this.handleRemoveFilter
className="pointer"
className= this.state.selectedCategoryId === 0 ? 'active' : ''
>All tags</a>
categoryItems
</div>









share|improve this question
























  • Hi, I want to help but I didn't really understand the problem. Please try to be clear about what you EXPECT to happen and what IS happening.

    – Sagi Rika
    Mar 26 at 8:03











  • please put here relevant code frok and show us link(it will be easier to help you):stackblitz.com/edit/react-pzyyha

    – לבני מלכה
    Mar 26 at 8:06






  • 1





    Why did you use "className" twice ?

    – Ibra
    Mar 26 at 8:07











  • Can you share the whole component?

    – Dehan de Croos
    Mar 26 at 8:31












  • I Really didn't thinks that made the problem! thanks

    – Hamed Rahmani
    Mar 26 at 9:10

















0















I want to set the active class dynamically in react.js but it's not working!
I'm using the setState() method to change the selected item.



this line of code not work .
className=selectedCategoryId === item.id ? 'active' : ''



I think the setState() function does not work correctly...



const open, selectedProduct, productCategory, filteredProducts, selectedCategoryId = this.state;
const categoryItems = productCategory.map((item) =>
<a key=item.id
onClick=() => this.handleFilter(item.id)
className=selectedCategoryId === item.id ? 'active' : ''
// className=()=>this.isActive(item.id)
className="pointer"
>item.value</a>
);


this does not change the class:



handleFilter = (id) => 
const filteredItem = this.state.productList.filter(x => x.categoryId == id);
this.setState(filteredProducts: filteredItem, selectedCategoryId: id);



but this change the className correctly when select I all tags:



handleRemoveFilter = () => 
this.setState(filteredProducts: this.state.productList, selectedCategoryId: 0);

//-------------------------------
<div className="tag-list">
<a onClick=this.handleRemoveFilter
className="pointer"
className= this.state.selectedCategoryId === 0 ? 'active' : ''
>All tags</a>
categoryItems
</div>









share|improve this question
























  • Hi, I want to help but I didn't really understand the problem. Please try to be clear about what you EXPECT to happen and what IS happening.

    – Sagi Rika
    Mar 26 at 8:03











  • please put here relevant code frok and show us link(it will be easier to help you):stackblitz.com/edit/react-pzyyha

    – לבני מלכה
    Mar 26 at 8:06






  • 1





    Why did you use "className" twice ?

    – Ibra
    Mar 26 at 8:07











  • Can you share the whole component?

    – Dehan de Croos
    Mar 26 at 8:31












  • I Really didn't thinks that made the problem! thanks

    – Hamed Rahmani
    Mar 26 at 9:10













0












0








0








I want to set the active class dynamically in react.js but it's not working!
I'm using the setState() method to change the selected item.



this line of code not work .
className=selectedCategoryId === item.id ? 'active' : ''



I think the setState() function does not work correctly...



const open, selectedProduct, productCategory, filteredProducts, selectedCategoryId = this.state;
const categoryItems = productCategory.map((item) =>
<a key=item.id
onClick=() => this.handleFilter(item.id)
className=selectedCategoryId === item.id ? 'active' : ''
// className=()=>this.isActive(item.id)
className="pointer"
>item.value</a>
);


this does not change the class:



handleFilter = (id) => 
const filteredItem = this.state.productList.filter(x => x.categoryId == id);
this.setState(filteredProducts: filteredItem, selectedCategoryId: id);



but this change the className correctly when select I all tags:



handleRemoveFilter = () => 
this.setState(filteredProducts: this.state.productList, selectedCategoryId: 0);

//-------------------------------
<div className="tag-list">
<a onClick=this.handleRemoveFilter
className="pointer"
className= this.state.selectedCategoryId === 0 ? 'active' : ''
>All tags</a>
categoryItems
</div>









share|improve this question
















I want to set the active class dynamically in react.js but it's not working!
I'm using the setState() method to change the selected item.



this line of code not work .
className=selectedCategoryId === item.id ? 'active' : ''



I think the setState() function does not work correctly...



const open, selectedProduct, productCategory, filteredProducts, selectedCategoryId = this.state;
const categoryItems = productCategory.map((item) =>
<a key=item.id
onClick=() => this.handleFilter(item.id)
className=selectedCategoryId === item.id ? 'active' : ''
// className=()=>this.isActive(item.id)
className="pointer"
>item.value</a>
);


this does not change the class:



handleFilter = (id) => 
const filteredItem = this.state.productList.filter(x => x.categoryId == id);
this.setState(filteredProducts: filteredItem, selectedCategoryId: id);



but this change the className correctly when select I all tags:



handleRemoveFilter = () => 
this.setState(filteredProducts: this.state.productList, selectedCategoryId: 0);

//-------------------------------
<div className="tag-list">
<a onClick=this.handleRemoveFilter
className="pointer"
className= this.state.selectedCategoryId === 0 ? 'active' : ''
>All tags</a>
categoryItems
</div>






javascript css reactjs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 8:21







Hamed Rahmani

















asked Mar 26 at 7:59









Hamed RahmaniHamed Rahmani

61 silver badge6 bronze badges




61 silver badge6 bronze badges












  • Hi, I want to help but I didn't really understand the problem. Please try to be clear about what you EXPECT to happen and what IS happening.

    – Sagi Rika
    Mar 26 at 8:03











  • please put here relevant code frok and show us link(it will be easier to help you):stackblitz.com/edit/react-pzyyha

    – לבני מלכה
    Mar 26 at 8:06






  • 1





    Why did you use "className" twice ?

    – Ibra
    Mar 26 at 8:07











  • Can you share the whole component?

    – Dehan de Croos
    Mar 26 at 8:31












  • I Really didn't thinks that made the problem! thanks

    – Hamed Rahmani
    Mar 26 at 9:10

















  • Hi, I want to help but I didn't really understand the problem. Please try to be clear about what you EXPECT to happen and what IS happening.

    – Sagi Rika
    Mar 26 at 8:03











  • please put here relevant code frok and show us link(it will be easier to help you):stackblitz.com/edit/react-pzyyha

    – לבני מלכה
    Mar 26 at 8:06






  • 1





    Why did you use "className" twice ?

    – Ibra
    Mar 26 at 8:07











  • Can you share the whole component?

    – Dehan de Croos
    Mar 26 at 8:31












  • I Really didn't thinks that made the problem! thanks

    – Hamed Rahmani
    Mar 26 at 9:10
















Hi, I want to help but I didn't really understand the problem. Please try to be clear about what you EXPECT to happen and what IS happening.

– Sagi Rika
Mar 26 at 8:03





Hi, I want to help but I didn't really understand the problem. Please try to be clear about what you EXPECT to happen and what IS happening.

– Sagi Rika
Mar 26 at 8:03













please put here relevant code frok and show us link(it will be easier to help you):stackblitz.com/edit/react-pzyyha

– לבני מלכה
Mar 26 at 8:06





please put here relevant code frok and show us link(it will be easier to help you):stackblitz.com/edit/react-pzyyha

– לבני מלכה
Mar 26 at 8:06




1




1





Why did you use "className" twice ?

– Ibra
Mar 26 at 8:07





Why did you use "className" twice ?

– Ibra
Mar 26 at 8:07













Can you share the whole component?

– Dehan de Croos
Mar 26 at 8:31






Can you share the whole component?

– Dehan de Croos
Mar 26 at 8:31














I Really didn't thinks that made the problem! thanks

– Hamed Rahmani
Mar 26 at 9:10





I Really didn't thinks that made the problem! thanks

– Hamed Rahmani
Mar 26 at 9:10












3 Answers
3






active

oldest

votes


















0














If setState() works well, try this :



<a onClick=this.handleRemoveFilter
className= this.state.selectedCategoryId === 0 ? 'pointer active' : 'pointer'
>All tags</a>






share|improve this answer























  • that's work, thanks :) . I had i mistake and use className twice...

    – Hamed Rahmani
    Mar 26 at 9:06



















0














store classname in state along with selected item. You can just update the classname in state whenever required.



for eg,



 <a key=item.id
onClick=() => this.handleFilter(item.id)
className=this.state.activeClassName


where active classname can be updated inside handlefilter






share|improve this answer






























    0














    One of the most common ways is to use classnames which you can conditionally joining classNames together



    var classNames = require('classnames');

    class Button extends React.Component
    // ...
    render ()
    var btnClass = classNames(
    btn: true,
    'btn-pressed': this.state.isPressed,
    'btn-over': !this.state.isPressed && this.state.isHovered
    );
    return <button className=btnClass>this.props.label</button>;








    share|improve this answer























    • i wanna set className dynamically but className=selectedCategoryId === item.id ? 'active' : '' not work .

      – Hamed Rahmani
      Mar 26 at 8:20











    • The correct way to write is className=classNames(active: selectedCategoryId === item.id)

      – Tony Yip
      Mar 26 at 8:22













    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55352295%2fhow-to-toggle-classname-dynamically-in-react-js%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    If setState() works well, try this :



    <a onClick=this.handleRemoveFilter
    className= this.state.selectedCategoryId === 0 ? 'pointer active' : 'pointer'
    >All tags</a>






    share|improve this answer























    • that's work, thanks :) . I had i mistake and use className twice...

      – Hamed Rahmani
      Mar 26 at 9:06
















    0














    If setState() works well, try this :



    <a onClick=this.handleRemoveFilter
    className= this.state.selectedCategoryId === 0 ? 'pointer active' : 'pointer'
    >All tags</a>






    share|improve this answer























    • that's work, thanks :) . I had i mistake and use className twice...

      – Hamed Rahmani
      Mar 26 at 9:06














    0












    0








    0







    If setState() works well, try this :



    <a onClick=this.handleRemoveFilter
    className= this.state.selectedCategoryId === 0 ? 'pointer active' : 'pointer'
    >All tags</a>






    share|improve this answer













    If setState() works well, try this :



    <a onClick=this.handleRemoveFilter
    className= this.state.selectedCategoryId === 0 ? 'pointer active' : 'pointer'
    >All tags</a>







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 26 at 8:12









    IbraIbra

    4502 silver badges9 bronze badges




    4502 silver badges9 bronze badges












    • that's work, thanks :) . I had i mistake and use className twice...

      – Hamed Rahmani
      Mar 26 at 9:06


















    • that's work, thanks :) . I had i mistake and use className twice...

      – Hamed Rahmani
      Mar 26 at 9:06

















    that's work, thanks :) . I had i mistake and use className twice...

    – Hamed Rahmani
    Mar 26 at 9:06






    that's work, thanks :) . I had i mistake and use className twice...

    – Hamed Rahmani
    Mar 26 at 9:06














    0














    store classname in state along with selected item. You can just update the classname in state whenever required.



    for eg,



     <a key=item.id
    onClick=() => this.handleFilter(item.id)
    className=this.state.activeClassName


    where active classname can be updated inside handlefilter






    share|improve this answer



























      0














      store classname in state along with selected item. You can just update the classname in state whenever required.



      for eg,



       <a key=item.id
      onClick=() => this.handleFilter(item.id)
      className=this.state.activeClassName


      where active classname can be updated inside handlefilter






      share|improve this answer

























        0












        0








        0







        store classname in state along with selected item. You can just update the classname in state whenever required.



        for eg,



         <a key=item.id
        onClick=() => this.handleFilter(item.id)
        className=this.state.activeClassName


        where active classname can be updated inside handlefilter






        share|improve this answer













        store classname in state along with selected item. You can just update the classname in state whenever required.



        for eg,



         <a key=item.id
        onClick=() => this.handleFilter(item.id)
        className=this.state.activeClassName


        where active classname can be updated inside handlefilter







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 8:08









        Gaurav MithasGaurav Mithas

        13 bronze badges




        13 bronze badges





















            0














            One of the most common ways is to use classnames which you can conditionally joining classNames together



            var classNames = require('classnames');

            class Button extends React.Component
            // ...
            render ()
            var btnClass = classNames(
            btn: true,
            'btn-pressed': this.state.isPressed,
            'btn-over': !this.state.isPressed && this.state.isHovered
            );
            return <button className=btnClass>this.props.label</button>;








            share|improve this answer























            • i wanna set className dynamically but className=selectedCategoryId === item.id ? 'active' : '' not work .

              – Hamed Rahmani
              Mar 26 at 8:20











            • The correct way to write is className=classNames(active: selectedCategoryId === item.id)

              – Tony Yip
              Mar 26 at 8:22















            0














            One of the most common ways is to use classnames which you can conditionally joining classNames together



            var classNames = require('classnames');

            class Button extends React.Component
            // ...
            render ()
            var btnClass = classNames(
            btn: true,
            'btn-pressed': this.state.isPressed,
            'btn-over': !this.state.isPressed && this.state.isHovered
            );
            return <button className=btnClass>this.props.label</button>;








            share|improve this answer























            • i wanna set className dynamically but className=selectedCategoryId === item.id ? 'active' : '' not work .

              – Hamed Rahmani
              Mar 26 at 8:20











            • The correct way to write is className=classNames(active: selectedCategoryId === item.id)

              – Tony Yip
              Mar 26 at 8:22













            0












            0








            0







            One of the most common ways is to use classnames which you can conditionally joining classNames together



            var classNames = require('classnames');

            class Button extends React.Component
            // ...
            render ()
            var btnClass = classNames(
            btn: true,
            'btn-pressed': this.state.isPressed,
            'btn-over': !this.state.isPressed && this.state.isHovered
            );
            return <button className=btnClass>this.props.label</button>;








            share|improve this answer













            One of the most common ways is to use classnames which you can conditionally joining classNames together



            var classNames = require('classnames');

            class Button extends React.Component
            // ...
            render ()
            var btnClass = classNames(
            btn: true,
            'btn-pressed': this.state.isPressed,
            'btn-over': !this.state.isPressed && this.state.isHovered
            );
            return <button className=btnClass>this.props.label</button>;









            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 26 at 8:11









            Tony YipTony Yip

            1206 bronze badges




            1206 bronze badges












            • i wanna set className dynamically but className=selectedCategoryId === item.id ? 'active' : '' not work .

              – Hamed Rahmani
              Mar 26 at 8:20











            • The correct way to write is className=classNames(active: selectedCategoryId === item.id)

              – Tony Yip
              Mar 26 at 8:22

















            • i wanna set className dynamically but className=selectedCategoryId === item.id ? 'active' : '' not work .

              – Hamed Rahmani
              Mar 26 at 8:20











            • The correct way to write is className=classNames(active: selectedCategoryId === item.id)

              – Tony Yip
              Mar 26 at 8:22
















            i wanna set className dynamically but className=selectedCategoryId === item.id ? 'active' : '' not work .

            – Hamed Rahmani
            Mar 26 at 8:20





            i wanna set className dynamically but className=selectedCategoryId === item.id ? 'active' : '' not work .

            – Hamed Rahmani
            Mar 26 at 8:20













            The correct way to write is className=classNames(active: selectedCategoryId === item.id)

            – Tony Yip
            Mar 26 at 8:22





            The correct way to write is className=classNames(active: selectedCategoryId === item.id)

            – Tony Yip
            Mar 26 at 8:22

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55352295%2fhow-to-toggle-classname-dynamically-in-react-js%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript