Skip to content
safwan39 edited this page Apr 28, 2021 · 7 revisions

usage 1:

passing the value directly in setState

class CustomComponent extends Component{
    var $state = ['counter' => 1];
    
    function componentDidUpdate($prevState, $currState){} //run only when there's state update
    
    function render(){
        $counter = $this->state->counter;
        
        return new div([ 
            new div("my state: $counter"),
            new button("increment state", ['onclick'=> "this.setState({counter: ".($counter+1)."})"]) 
        ]); //must wrap the component with html tag
    }
}

usage 2:

using old state

class CustomComponent extends Component{
    var $state = ['counter' => 1];
    
    function componentDidUpdate($prevState, $currState){} //run only when there's state update
    
    function render(){
        $counter = $this->state->counter;
        
        return new div([ 
            new div("my state: $counter"),
            new button("increment state", ['onclick'=> "this.setState(prevState => ({counter: prevState.counter +1 }))"]) 
        ]); //must wrap the component with html tag
    }
}

get state in javascript

class CustomComponent extends Component{
   var $state = ['counter' => 1];
   
   function render(){
       $counter = $this->state->counter;
       
       return new div([ 
           new div($counter, ['id'=> 'counter']),
           new button("increment state", ['onclick'=> "var state = this.getState(); document.getElementById('counter').innerText = state.counter + 1 "]) //second param of set state
       ]);     
  }
}

keep focus on the input when state changed

there's issue when re-rendering component the input loses the focus to handle that we must add key prop to the input tag

class CustomComponent extends Component{
   var $state = ['counter' => 1];
   
   function render(){
       $counter = $this->state->counter;
       
       return new div([ 
           new input(['value'=> $counter, 'type'=> 'number', 'onkeyup'=> 'this.setState({counter: parseInt(this.value)})']),
       ]);     
  }
}

hook after state changed

class CustomComponent extends Component{
    var $state = ['counter' => 1];
    
    function componentDidUpdate($prevState, $currState){} //run only when there's state update
    
    function render(){
        $counter = $this->state->counter;
        
        return new div([ 
            new div("my state: $counter"),
            new button("increment state", ['onclick'=> "this.disabled=true; this.setState(prevState => ({counter: prevState.counter +1 }), ()=> this.disabled=false)"]) //second param of set state
        ]);     
   }
}
Clone this wiki locally