Skip to content Skip to sidebar Skip to footer

React Js - Change Color On Click And Put Defaul Color On All Other Ones

I have 'x' number of rendered ArticlePreview components that depends of API call. I can change color of div from specific component when I click on it. But whet I click to anoth

Solution 1:

By leveraging state management, you can achieve that. Please find below sample for reference. Avoid DOM Manipulations and let react take care of that.

constArticlePreview = (props) => {
  return(
    <divclassName={props.class}onClick={props.onClick}>{props.article}</div>
  )
}

classAppextendsReact.Component {

  constructor(props) {
    super(props)
    this.state={
      selected: false,
      article: ''
    }
  }
  
  onSelectArticle = (article) => {
   this.setState({
     selected:true,
     article:article
   })
  }
  
  render() {
    let articles = ['one', 'two', 'three']
    
    return<div>
    {
      articles.map((article, index)=> <ArticlePreviewkey={index}class={(this.state.selected && (this.state.article === article)) ? 'bkcolor': 'default'} onClick={() => this.onSelectArticle(article)} article={article}/>)
    }
    </div>
  }
}

ReactDOM.render( <App/> , document.getElementById("app"))
.default {
  background: transparent
}
.bkcolor {
  background: red
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><divid="app"></div>

In your case, pass the index to the handler and check the selected and match the index state.

 ...
<ArticlePreview className={(this.state.selected && (this.state.index === index)) ? 'bkcolor': 'default'} onClick={()=>this.props.clicked(index)} img={images[index]} title={titles[index]} description={descriptions[index]} key={i}> </ArticlePreview>) }) }
 ...

Solution 2:

As Dev's Answer it is a better way to use React props and state.

It is necessary to pass the click Handler function to div because onClick props works on DOM elements but React.Component.

This is my example and it is similar with @Dev's

You can refer to https://reactjs.org/docs/handling-events.html for more info.

Post a Comment for "React Js - Change Color On Click And Put Defaul Color On All Other Ones"