0

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>
    );
  }
}

2 Answers2

1

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.

Rodentman87
  • 640
  • 7
  • 14
0

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 */
}
Mosia Thabo
  • 4,009
  • 1
  • 14
  • 24