Pulse7
8/1/2017 - 10:10 PM

React git api user card example, fetch example, spread example, <div>{array}</div> example

React git api user card example, fetch example, spread example,

{array}
example

const Card = function(props) {
    return (
        <div style={{
            margin: '1em'
        }}>
            <img width="75" src={props.avatar_url}/>
            <div style={{
                display: "inline-block",
                marginLeft: "10px"
            }}>
                <div style={{
                    fontSize: "1.25em",
                    fontWeight: "bold"
                }}>{props.name}</div>
                <div>{props.company}</div>
            </div>
        </div>
    );
}

const CardList = (props) => {
    return (
        <div>

            {props.cards.map(card => (<Card key={card.id} {...card}/>))}
        </div>
    )
}

class Form extends React.Component {
    state={
            userName:""
    };

    handleSubmit = (event)=>{
        event.preventDefault();
        fetch("https://api.github.com/users/"+this.state.userName)
            .then(response=>response.json())
            .then(json=>this.props.onSubmit(json));
        this.setState({userName:""});
    }
    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <input  value={this.state.userName}
                        onChange={(event)=>this.setState({userName:event.target.value})}
                        type="text"
                        placeholder="Github username"
                        />
                <button  type="submit">Add card
                </button>
            </form>
        )
    }
}

class App extends React.Component {
    state = {
        cards: []
    };

    addNewCard = (cardInfo) =>{
        this.setState(prevState=>({cards:prevState.cards.concat(cardInfo)}))
    }

    render() {
        return (
            <div>
                <Form onSubmit={this.addNewCard}/>
                <CardList cards={this.state.cards}/>
            </div>
        )
    }
}

let nodeSlot = document.getElementById("container");
ReactDOM.render(<App/>, nodeSlot);