The Github Cards App
Código de exemplo feito no curso de React de Pluralsight empregando sintaxe de clase:
class Card extends React.Component {
render() {
const profile = this.props
return (
<div className="github-profile">
<img src={profile.avatar_url}/>
<div className="info">
<div className="name">{profile.name}</div>
<div className="company">{profile.company}</div>
</div>
</div>
)
}
}
class Form extends React.Component {
state = { userName: '' }
handleSubmit = async (event) => {
event.preventDefault()
const resp = await axios.get(`https://api.github.com/users/${this.state.userName}`)
this.props.onSubmit(resp.data)
this.setState({ userName: '' })
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Github username"
value={this.state.userName}
onChange={event => this.setState({ userName: event.target.value })}
required
/>
<button>Add card</button>
</form>
)
}
}
const CardList = (props) => (
<div>
{props.profiles.map(profile => <Card key={profile.id} {...profile} />)}
</div>
)
class App extends React.Component {
constructor(props) {
super(props)
// Inicializar state en class components.
// Sería o equivalente a useState()
this.state = {
profiles: []
}
}
addNewProfile = (profileData) => {
this.setState(prevState => ({
// Concatenamos os perfiles anteriores co novo e actualizamos o estado
profiles: [...prevState.profiles, profileData]
}))
}
render() {
return (
<div>
<div className="header">{this.props.title}</div>
<Form onSubmit={this.addNewProfile} />
<CardList profiles={this.state.profiles} />
</div>
)
}
}
ReactDOM.render(
<App title="The GitHub Cards App" />,
mountNode,
);
CSS:
/* Nerdy secret: You can use "less" below! Don't tell anybody... */
.github-profile {
margin: 1rem;
img {
width: 75px;
}
.info {
display: inline-block;
margin-left: 12px;
.name {
font-size: 1.25rem;
font-weight: bold;
}
}
}
form {
border: thin solid #ddd;
background-color: #fbfbfb;
padding: 2rem;
margin-bottom: 2rem;
display: flex;
justify-content: center;
}
.header {
text-align: center;
font-size: 1.5rem;
margin-bottom: 1rem;
}