Skip to content

Instantly share code, notes, and snippets.

@anandof28
Created October 11, 2018 10:53
Show Gist options
  • Select an option

  • Save anandof28/8901764d2d656fd8c2a6032d9ba13a36 to your computer and use it in GitHub Desktop.

Select an option

Save anandof28/8901764d2d656fd8c2a6032d9ba13a36 to your computer and use it in GitHub Desktop.
import React from "react";
import { render } from "react-dom";
import "bootstrap/dist/css/bootstrap.css";
/**
* State
* -> Another way to represent data in react
* -> It is ment for biz logic
* -> State is maintained, changed by a component itself
* -> State is Changed by biz logic
* -> Whenever teh state is changed, UI is repainted
*
* Biz Logic
* -> It is function, Listener Function - Callback Function
* -> It is Associated with "Event"
*
* How to represent state data?
* React Component has instance variable called "state"
*
* Node: State Can be used only inside "Class" component only
* Prop can be used inside class and also function
*/
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
comment : ["First Comment", "Second Comment", "Third Comment"],
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.SelectedComment = this.SelectedComment.bind(this);
}
handleChange(event) {
//console.log(this._inputElement.value);
}
handleSubmit(event) {
if (this._inputElement.value !== "") {
let entered_value = this._inputElement.value
let data = this.state.comment;
this.setState({
comment : data.concat(entered_value)
});
this._inputElement.value = "";
}
event.preventDefault();
}
SelectedComment(e){
var array = this.state.comment;
var index = array.indexOf(e); // Let's say it's Bob.
delete array[index];
this.setState({comment: array});
}
render() {
return (
<div className="container">
<h1>Your Valuable Comments</h1>
<ul className="list-group">
{
this.state.comment.map((item,index) => {
return(
<li className="list-group-item d-flex justify-content-between align-items-center" key={index}>{item}
<span className="badge badge-danger" onClick={() => {this.SelectedComment(item);}} >X</span>
</li>
)
})
}
</ul>
<hr/>
<div>
<h1>Provide Your Comments:</h1>
<form onSubmit={this.handleSubmit} >
<label >Comment:</label>
<textarea className="form-control" ref={(a) => this._inputElement = a} onChange={this.handleChange} /><br/>
<input className="btn btn-primary" type="submit" value="Submit You Comment" />
</form>
</div>
</div>
);
}
}
render(<App />, document.getElementById("root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment