IAspireToBeGladOS
IAspireToBeGladOS

Reputation: 1484

Conditional formatting in React - adding or appending CSS classes

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?

Upvotes: 1

Views: 147

Answers (1)

Joru
Joru

Reputation: 4436

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.

Upvotes: 5

Related Questions