Accepted answer

you are mutating the original state. dont mutate the state, and use setstate to rerender the ui.

addtolist() {
   let k = [...this.state.alltasks];
   this.setstate({alltasks: k})

addtolist() {
   this.setstate({alltasks: [...this.state.alltasks, this.state.inputvalue]})

directly changing the state does not rerender the ui. you should avoid mutating state directly. also using setstate to update the state will rerender the ui.

let k = [...this.state.alltasks]; creates a new array, and then we push a value to k. so in this case we are not mutating the state directly. instead we are changing a newly created array. after that we are using setstate to set the state which will update the ui.


here goes your answer:

class app extends component {
   constructor(props) {
       this.state = {
          inputvalue: '',
          alltasks: []

       this.addtolist = this.addtolist.bind(this);

   addtolist(e) {
      if( e && e.preventdefault ) e.preventdefault();
         alltasks: [...this.state.alltasks, this.state.inputvalue]

   render() {
       return (
             <h1>کار های خود را مدیریت کنید !</h1>
             <input type="text" placeholder="کار خود را بنویسید ..." value={this.state.inputvalue} onchange={ event => this.setstate({ inputvalue: }) } />
             <button onclick={ e => this.addtolist(e) }>ثبت کردن</button>
             <hr />
          => {
                     return <li>{ task }</li>;

here this.setstate updates the state and [...alltasks, this.state.inputvalue] appends the inputvalue to the array of alltasks. the changing in state makes the component rerender it and hence the updated value will be visible in your list.

Related Query

More Query from same tag