Jordan Raleigh
Jordan Raleigh

Reputation: 13

Trying to change the css class using a button in JSX React

I am trying to write a react class where the render function contains a button which once clicked, it changes the css class from one to another as well as changes the text from available to taken. The text change is working but not the CSS change. I am not sure where I am going wrong in my code below. I also tried to write a toggle class function in my class methods which isn't switching as well. Not too strong in html and JSX so any help would be appreciated. Thanks.


class Singles extends React.Component {
  constructor() {
    super();
    this.state = {
      isSingle: false,
    };
  }
  toggleIsSingle() {
    this.setState({
      isSingle: !this.state.isSingle
    });
  }
  render() {
    const { name, description, id } = this.props.pet;
    const isSingle = this.state.isSingle;
    return (
      <div
        key={id}
        className={this.state.isSingle ? 'single.taken' : 'single'}
      >
        <div id="info">
          <p>{name}</p>
          <p>{description}</p>
          <div>{this.state.isSingle ? 'Taken!' : 'Available'}</div>
          <button onClick={() => this.toggleIsSingle()}>Toggle Status</button>
        </div>
      </div>
    );
  }
}

Upvotes: 0

Views: 109

Answers (2)

Mosia Thabo
Mosia Thabo

Reputation: 4267

Very Important:

class naming rules:

  • Must begin with a letter A-Z or a-z
  • Can be followed by: letters (A-Za-z), digits (0-9), hyphens ("-"), and underscores ("_")

As already noted by @Rodentman87 the problem by far lies on your class naming rule.

className={this.state.isSingle ? 'single.taken' : 'single'} here with the period ., try using a valid character( e.g - or _) for class names.

OR as an alternative, you could try the following:

className={this.state.isSingle ? 'single taken' : 'single'} here you have single and taken as part of your className which will allow you to select the taken single using

CSS:

.single.taken{
  /* Your taken Single Style here */
}

Upvotes: 0

Rodentman87
Rodentman87

Reputation: 650

The issue you have here is with your class name, a . is a reserved character for CSS class names, so single.taken is an invalid name, and you would need to switch it to something like single-taken

For more info on valid CSS class names, take a look at this thread.

Upvotes: 1

Related Questions