2

Hi guys currently I have a problem on conditional rendering in react.

I have 2 arrays saved in state :

this.state = {
   arr_one:[1,2,3,4,5],
   arr_two:[1,3,5]
};

I want to render divs iteration with those array and the condition if items in arr_two exists in arr_one, then render the differents divs.

note : I don't want to fix this with modulus condition (%).

Here's my code :

Code :

class TestComp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            arr_one:[1,2,3,4,5],
            arr_two:[1,3,5]
        };
    }


    render() {
        const filteredStyle={
            background:'red'
        }
        return (
            <div className="wrapper">
            {
                this.state.arr_one.map((item,index)=>
                    index === this.state.arr_two[index]?
                        <div key={index} className={filteredStyle}>
                            <p>Item {item}</p>
                        </div>
                    : 
                        <div key={index}>
                            <p>I'm not in filter! {item}</p>
                        </div>
                )               
            }

            </div>
        )
    }
}

Output :

I'm not in filter! 1

I'm not in filter! 2

I'm not in filter! 3

I'm not in filter! 4

I'm not in filter! 5

Expected Output :

Item 1

I'm not in filter! 2

Item 3

I'm not in filter! 4

Item 5

I also have my code demo in CodeSandBox

2 Answers 2

3

You can fix the condition index === this.state.arr_two[index] using includes, to:

this.state.arr_two.includes(item)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks aprill, that's what I want 😇Sorry for asking this simple question cos I'm still learning on iteration 😅
0

You are comparing index of arr_one with value of arr_two

And I don't understand during your arr_one have value equals 0 but your output isn't

1 Comment

Yeah edited. and it's actually arrays saved on state 😅

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.