0

I wanted to update this variable when the condition is true, but it doesn't let me, thanks

 constructor(props){
        super(props);
        var isActive = false;

        this.props.items.map(item => (
                if(item.name == this.props.product.name) {
                    isActive = true;
                }
        ));

        this.state = {
            active: isActive
        };

        console.log(isActive);
        this.handleClick = this.handleClick.bind(this);

    }
4
  • Are there any errors in the Javascript console? That doesn't look like valid Javascript syntax, but I don't know if react fixes it up. Commented Mar 24, 2017 at 19:47
  • In normal JS you can't have if inside parentheses, you should have {} around the function body. Commented Mar 24, 2017 at 19:48
  • 1
    why not setState? Commented Mar 24, 2017 at 19:57
  • 2
    because is in the constructor, we cannot call setState in the constructor Commented Mar 24, 2017 at 19:58

2 Answers 2

1

Reason is, you forgot to use {}, If you are using any condition or wants to do some calculation use {} and put all the statement inside that. One more thing since you just want to iterate the array means not returning anything, so i that case use forEach instead of map, Use this:

this.props.items.forEach(item => { //here
    if(item.name == this.props.product.name) {
          isActive = true;
    }
});

Check this code it will produce the same error:

[1,2,3,4].forEach(el=>(
     if(el % 2 == 0)
         console.log(el);
))

Check the working example:

[1,2,3,4].forEach(el=>{
         if(el % 2 == 0)
             console.log(el);
})

Sign up to request clarification or add additional context in comments.

2 Comments

it should be like this: this.props.items.forEach((item) => { //here if(item.name == this.props.product.name) { isActive = true; } });
@Ved didn't get you, what's the difference ? he is using single argument so () is not required with item. That is useful when someone need the index also, means multiple arguments :)
0

You really aren't passing an 'active' property nor state. You are trying to set a computed property, much like Ember (see How to setup Ember like computed properties in Immutablejs and Redux and Flux and React). This was considered for React and dismissed.

You should just create a function, isActive() and call it when needed. I expect you only need it when rendering a set of individual item components for which isActive is a property.

That said, there are ways of cramming this into a React codebase, but your code will be unmaintainable.

Comments

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.