Created
April 19, 2018 07:41
-
-
Save gyurisc/aac95d502277cc050f1193671b82a381 to your computer and use it in GitHub Desktop.
Simple React.js example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// to run this use: https://jscomplete.com/repl | |
import React from 'react'; | |
import { render } from 'react-dom'; | |
const Card = (props) => { | |
return ( | |
<div style={{margin: '1em'}}> | |
<img width="75" src={props.avatar_url} /> | |
<div style={{display: 'inline-block', marginLeft: 10}}> | |
<div style={{fontSize: '1.25em', fontWieght: 'bold'}}> | |
{props.name} | |
</div> | |
<div>{props.company}</div> | |
</div> | |
</div> | |
); | |
}; | |
let data = [ | |
{ | |
name: "Paul O’Shannessy", | |
avatar_url: "https://avatars1.githubusercontent.com/u/8445?v=4", | |
company: "Facebook" | |
}, | |
{ | |
name: "Gyuris Gellért", | |
avatar_url: "https://avatars0.githubusercontent.com/u/847982?v=4", | |
company: "Szent András Evangelizációs Alapítvány" | |
}, | |
{ | |
"avatar_url": "https://avatars1.githubusercontent.com/u/790821?v=4", | |
"name": "gyurisc", | |
"company": null, | |
"blog": "http://www.littlebigtomatoes.com/", | |
"location": "Budapest" | |
} | |
]; | |
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(); | |
axios.get(`https://api.github.com/users/${this.state.userName}`) | |
.then(resp => { | |
this.props.onSubmit(resp.data); | |
this.setState({ userName: '' }); | |
}); | |
}; | |
render () { | |
return ( | |
<form onSubmit={this.handleSubmit}> | |
<input type="text" | |
value={this.state.userName} | |
onChange={(event) => this.setState({ userName: event.target.value })} | |
placeholder="Github username" /> | |
<button>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> | |
); | |
} | |
} | |
ReactDOM.render(<App />, mountNode); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment