0

a bit new to react. I used the create react app https://github.com/facebook/create-react-app to start a new react project.

the full code is here. https://github.com/bryandellinger/reactswitch/tree/master/src

I am trying to get the background color of a selected element to change and the text to become bold but it appears the class is never added not sure what I am doing wrong.

Switch.js

import React, { PropTypes } from 'react';
import  styles from './Switch.css';

const CREDITCARD = 'Creditcard';
const BTC = 'Bitcoin';


const Choice = function (props) {
  const cssClasses = [];

  if (props.active) {
    // <-- check props, not state
    cssClasses.push(styles.active);
  }

  return (
    <div
      onClick={props.onClick}
      className={cssClasses}
    >
      {props.label} {/* <-- allow any label */}
    </div>
  );
};

class Switch extends React.Component {
  state = {
    payMethod: BTC,
  };

  select = (choice) => {
    return (evt) => {
      this.setState({
        payMethod: choice,
      });
    };
  };

  render() {
    return (
      <div className='switch'>
        <Choice
          onClick={this.select(CREDITCARD)}
          active={this.state.payMethod === CREDITCARD}
          label='Pay with Creditcard'
        />

        <Choice
          onClick={this.select(BTC)}
          active={this.state.payMethod === BTC}
          label='Pay with Bitcoin'
        />

        Paying with: {this.state.payMethod}
      </div>
    );
  }
}

export default Switch;

and Switch.css

.active {
    background-color: #4619eb;
    font-weight: bold; 
  }

it appears the active class from switch.css never gets added on the onclick event. not sure what I am missing.

2 Answers 2

1

Because of the way webpack is configured in CRA, you need to write your css like this:

 :local(.active) {
    background-color: #4619eb;
    font-weight: bold; 
  }
Sign up to request clarification or add additional context in comments.

Comments

1

CRA only supports importing the whole CSS file directly out of the box. So instead of importing the CSS file as a component, you would do:

import './Switch.css';

CRA docs for adding a stylesheet: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-a-stylesheet

Also, the className property should be a string with class names separated with a while space. If you want to set the class name dynamically, check out classnames: https://github.com/JedWatson/classnames.

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.