0

I have the following line:

<button className={`actionBoxButton ${props.moves[0].moveName !== "FirstPassMove" && props.moves[0].moveName !== "PassMove"  ? "actionBoxButtonGrey" : ''}`}

What it does is to check if the object "moves" has the value "FirstPassMove" for the key moveName. If so, I want it so switch to another style. This is working well. But what I want to achieve is, to not only check the element 0 of the object, but all the objects and check if there is a moveName "FirstPassMove" in any element of the object. It is written in React 16.12

Thanks!

4 Answers 4

1

You can simplify your jsx by defining a separate function for dynamic className like this:

const check = () => {
	let className_ = "";
    // if this.props.moves is an array, use of instead of in
	for(let i in this.props.moves) {
		if((this.props.moves[i].moveName !== "FirstPassMove") && (this.props.moves[i].moveName !== "PassMove")) {
			className_ = "actionBoxButtonGrey";
		}
	}

	return className_;
}
<button className={this.check()}>button</button>

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

1 Comment

cool, thanks for that! the idea of using an external function with a for loop really did solve the problem for me
0
props.moves.includes('FirstPassMove')

Assuming your props.moves is an array it will return true or false if this string is inside the props.moves array

Comments

0

If you want to add className in case at least one of your moves has FirstPassMove or PassMove name you should use Array.prototype.some()

const hasPass = moves.some(({ moveName }) => (
  moveName === "FirstPassMove" || 
  moveName === "PassMove"
));

Comments

0

I am guessing you want to check that all the moves satisfy the constraint, in which case, you can use Array.prototype.every to ensure every move satisfies the constraint. If you only need some moves to satisfy the constraint, you may use Array.prototype.some instead.

// For example
const props = {
    moves: [
        { moveName: 'FirstPassMove' },
        { moveName: 'PassMove' },
        { moveName: 'PassMove' },
        { moveName: 'OtherPassMove' },
    ]
};

function isValidMove({ moveName }) {
    return moveName !== "FirstPassMove"
        && moveName !== "PassMove";
}


function getActionBoxButtonClassName(hasColor) {
    return `actionBoxButton ${hasColor ? "actionBoxButtonGrey" : ''}`;
}

console.log([
    getActionBoxButtonClassName(props.moves.every(isValidMove)),
    getActionBoxButtonClassName(props.moves.some(isValidMove))
]);

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.