user11067258
user11067258

Reputation:

React Component div id will not hide what used in map loop

I have this code in an index.html file which loads with the application:

$(window).on('load', () => {
    $('#one').hide();
    $('#oneb').hide();
});

And this affects the component:

import React from 'react';

const Test = (props) => <div id="MyDiv">


    <div>

        <div id="one">
            THIS IS ONE
        </div>


        {

            props.list.map((data, i) => {

                return <div id="oneb" key={i}>
                   THIS IS ONEB
                </div>

            })

        }


    </div>
</div>

What is happening here is that div with id="one" will hide BUT id="oneb" will still show up.

Why is this happening? How can I fix this?

Upvotes: 0

Views: 34

Answers (1)

lomse
lomse

Reputation: 4165

You are not doing it the React way. To do it the React way, your component should hold and manipulate some kind of state. Check the example below:

import React from 'react';
class MyAwesomeComponent React.Component {
    constructor(){
        this.state = {
            hide: false
        }
    }
    render(){
        const {hide} = this.state;

        <React.Fragment>
            {
                hide
                ? null
                : <div>This is my awesome div that I need to show or hide ;)</div>
            }
            <button>{hide ? 'Show': 'Hide'}</button>
        </React.Fragment>
    }
}
export default MyAwesomeComponent;

The code above will hide or show your div. Check the React documentation

Upvotes: 2

Related Questions