1

What's a more concise way to apply conditional formatting to this statement?

const PaginationStorePageLink = ({ store, pageNum }) => (observer(({ PaginationStore }) => {
  if (this.props.store.currentPage === this.props.pageNum) {
    return (
      <PaginationLink className={styles.bold} onClick={this.props.store.goToPage(this.props.pageNum)} />
    );
  }
  return (
    <PaginationLink className={styles.primary} onClick={this.props.store.goToPage(this.props.pageNum)} />
  );
}));

Specifically, if the current page number is detected as being current, the ".bold" class should be applied. Otherwise, the ".primary" class should be applied.

As a related question, is it possible to append classes to each other? So for example, the ".primary" class is applied either way, but ".bold .primary" is applied if the conditions are met?

1

1 Answer 1

5

You can do something like this:

const PaginationStorePageLink = ({ store, pageNum }) => (observer(({ PaginationStore }) => {
  const style = store.currentPage === pageNum ? styles.bold : styles.primary;

  return (
    <PaginationLink className={style} onClick={store.goToPage(pageNum)} />
  );
}));

For the second question, you could apply both classes (".bold .primary") if you want styles from both CSS classes to be applied.

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

6 Comments

could also use an object to map styles to conditions. if there is a necessity for more then 2-3 styles id recommend going that approach so you don't get into ternary hell :) got my vote regardless! :)
Could you explain how it works, logically? Specifically, this line: this.props.pageNum ? styles.bold : styles.primary; - I see what you're doing, but want to make sure I understand why it works. :)
That's a ternary expression, it's equivalent to let style = styles.primary; if(this.props.store.currentPage === this.props.pageNum) style = styles.bold;. Basically picking out the right style to use with a conditional like you were doing in your original code, but storing it in a variable to avoid duplication.
Thank you, that makes sense!
So if I were modifying it to have both expressions by default: const style = this.props.store.currentPage === this.props.pageNumber ? styles.primary.bold : styles.primary; That would make styles.primary.bold the one activated by the conditional, and styles.primary would be the default?
|

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.