[javascript] How to add a class with React.js?

I need add class "active" after click to button and remove all other "active" classes.

Look here please: https://codepen.io/azat-io/pen/RWjyZX

var Tags = React.createClass({
  setFilter: function(filter) {
    this.props.onChangeFilter(filter);
  },
  render: function() {
    return <div className="tags">
      <button className="btn active" onClick={this.setFilter.bind(this, '')}>All</button>
      <button className="btn" onClick={this.setFilter.bind(this, 'male')}>male</button>
      <button className="btn" onClick={this.setFilter.bind(this, 'female')}>female</button>
      <button className="btn" onClick={this.setFilter.bind(this, 'child')}>child</button>
      <button className="btn" onClick={this.setFilter.bind(this, 'blonde')}>blonde</button>
     </div>
  }
});

var Kid = React.createClass({
  render: function() {
    return <ul>
      <li>{this.props.name}</li>
      </ul>
  }
});

var List = React.createClass({
  getInitialState: function() {
    return {
      filter: ''
    };
  },
  changeFilter: function(filter) {
    this.setState({
      filter: filter
    });
  },
  render: function() {
    var list = this.props.Data;

    if (this.state.filter !== '') {
      list = list.filter((i)=> i.tags.indexOf(this.state.filter) !== -1);
      console.log(list);
    } 

    list = list.map(function(Props){
      return <Kid {...Props} />
    });

    return <div>
      <h2>Kids Finder</h2>
      <Tags onChangeFilter={this.changeFilter}/>
      {list}
    </div>
  }
});

var options = {
  Data:  [{
    name: 'Eric Cartman',
    tags: ['male', 'child']
  },{
    name: 'Wendy Testaburger',
    tags: ['female', 'child']
  },{
    name: 'Randy Marsh',
    tags: ['male']
  },{
    name: 'Butters Stotch',
    tags: ['male', 'blonde', 'child']
  },{
    name: 'Bebe Stevens',
    tags: ['female', 'blonde', 'child']
  }]
};

var element = React.createElement(List, options);
React.render(element, document.body);

How do I make it better here?

This question is related to javascript jquery reactjs

The answer is


Since you already have <Tags> component calling a function on its parent, you do not need additional state: simply pass the filter to the <Tags> component as a prop, and use this in rendering your buttons. Like so:

Change your render function inside your <Tags> component to:

render: function() {
  return <div className = "tags">
    <button className = {this._checkActiveBtn('')} onClick = {this.setFilter.bind(this, '')}>All</button>
    <button className = {this._checkActiveBtn('male')} onClick = {this.setFilter.bind(this, 'male')}>male</button>
    <button className = {this._checkActiveBtn('female')} onClick = {this.setFilter.bind(this, 'female')}>female</button>
    <button className = {this._checkActiveBtn('blonde')} onClick = {this.setFilter.bind(this, 'blonde')}>blonde</button>
  </div>
},

And add a function inside <Tags>:

_checkActiveBtn: function(filterName) {
  return (filterName == this.props.activeFilter) ? "btn active" : "btn";
}

And inside your <List> component, pass the filter state to the <tags> component as a prop:

return <div>
  <h2>Kids Finder</h2> 
  <Tags filter = {this.state.filter} onChangeFilter = {this.changeFilter} />
  {list}
</div>

Then it should work as intended. Codepen here (hope the link works)


Taken from their site.

render() {
  let className = 'menu';
  if (this.props.isActive) {
    className += ' menu-active';
  }
  return <span className={className}>Menu</span>
}

https://reactjs.org/docs/faq-styling.html


this is pretty useful:

https://github.com/JedWatson/classnames

You can do stuff like

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'

or use it like this

var btnClass = classNames('btn', this.props.className, {
  'btn-pressed': this.state.isPressed,
  'btn-over': !this.state.isPressed && this.state.isHovered
});

you can also use pure js to accomplish this like the old ways with jquery

try this if you want a simple way

 document.getElementById("myID").classList.add("show-example");

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release