I am trying to create a chatbox component like the facebook-status post. There are buttons on the bottom. When a user clicks them I load various box styles. I need to set the class of current button "active".
My component is not controlled by a parent so I cannot set any prop bases solution. I know how to implement a ternary operator but don't know how can I use it here?
I have tried these solutions but these all are parent based. React Js conditionally applying class attributes react change the class of list item on click
import React from "react"
import StyleButton from "./StyleButton"
class Post extends React.Component {
constructor() {
super()
this.state = {
selectedClass: 'red',
displayBtns: true,
buttons: [1,2,3,4,5,6]
}
}
handleDisplayBtnClick = () => {
this.setState(prevState => ({
displayBtns: !prevState.displayBtns
}))
}
handleChange = e => {
let btnId = e.currentTarget.dataset.id;
switch (btnId) {
case '1':
this.setState({selectedClass: "purple" })
break;
case '2':
this.setState({selectedClass: "cyan" })
break;
case '3':
this.setState({selectedClass: "ballons" })
break;
case '4':
this.setState({selectedClass: "clouds" })
break;
case '5':
this.setState({selectedClass: "thumbs" })
break;
case '6':
this.setState({selectedClass: "smile" })
break;
default:
this.setState({selectedClass: "default" })
}
}
render() {
return(
<div className={`bg container ${this.state.selectedClass}`} >
<input className="input" placeholder="What's on your mind?" type="text"/>
<button className={this.state.displayBtns ? 'closeBtn' : 'openBtn'} onClick={this.handleDisplayBtnClick}> </button>
{ this.state.displayBtns ?
<div className="btns" >
{this.state.buttons.map(eachButtonNumber =>
<button
key={eachButtonNumber}
data-id={eachButtonNumber}
onClick={this.handleChange}
> </button>
)}
</div>
: null }
</div>
)
}
}
export default Post
I want to add an "active" class when I click it on the buttons which are rendered from "buttons.map". Right now my buttons is changing the Div class to change the background.
<button
key={eachButtonNumber}
data-id={eachButtonNumber}
onClick={this.handleChange} > </button>
Also, want to know If this is the right way of doing it?
Posted the whole code and GIF at "https://github.com/ankursehdev/facebook-post-box-reactjs"
My Rendered HTML - I want "active" on the list of buttons.
<div class="parent">
<div class="bg container smile">
<input class="input" placeholder="What's on your mind?" type="text">
<button class="closeBtn"> </button>
<div class="btns">
<button data-id="1"> </button>
<button data-id="2"> </button>
<button data-id="3"> </button>
<button data-id="4"> </button>
<button data-id="5"> </button>
<button data-id="6"> </button>
</div>
</div>
</div>