Wednesday, October 14, 2020

setting the state values through constructor and binding

 

//outer.js
import React, { Component } from 'react'

class Cars extends Component{
    render(){
    console.log(this.props);
     return(
     <div>
    <h3>from cars component</h3>
    <p>{this.props.msg}</p>
    <p>{this.props.model}</p>
    <div>{this.props.coolCars.map((item,i)=>{
return <p key={i}>{item}</p>;
})}</div>
    </div>
    );
    }
    }

export class Parent extends Component {
    constructor(props) {
        super(props)
    
        this.state = {
             cars: ['s-BMW','s-MERC','s-City','s-Audi']
        }
        this.handleClick=this.handleClick.bind(this);
    }
    
    handleClick(){
        this.setState({cars: this.state.cars.reverse()})
    }

    render() {
        return (
            <div>
                <h2 onClick={this.handleClick}>Just Click</h2>
                <Cars msg="cars are cool" model="34567" coolCars={this.state.cars}/>
            </div>
        )
    }

}
Parent.defaultProps={
    cars: ['BMW','MERC','City','Audi']
}

export default Cars

No comments:

Post a Comment