Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
Very simple example of a form that accepts a GitHub username and once it receives a submit
event, it asks the GitHub API for the user information, and prints them.
This code creates a reusable Card component. When you enter a name in the input
field managed by the Form component, this name is bound to its state.
When Add card is pressed, the input form is cleared by clearing the userName
state of the Form component.
The example uses, in addition to React, the Axios library. It’s a nice useful and lightweight library to handle network requests. Add it to the Pen settings in Codepen, or install it locally using npm install axios
.
Output
Code
We start by creating the Card
component, the one that will display our image and details as gathered from GitHub. It gets its data via props, using
props.avatar_url
the user avatarprops.name
the user nameprops.blog
the user website URLconst Card = props => { return ( <div style={{ margin: '1em' }}> <img alt="avatar" style={{ width: '70px' }} src={props.avatar_url} /> <div> <div style={{ fontWeight: 'bold' }}>{props.name}</div> <div>{props.blog}</div> </div> </div> ) }
We create a list of those components, which will be passed by a parent component in the cards
prop to CardList
, which iterates on it using map()
and outputs a list of cards:
const CardList = props => (
<div>
{props.cards.map(card => (
<Card {...card} />
))}
</div>
)
The parent component is App, which stores the cards
array in its own state, managed using the useState()
Hook:
const App = () => {
const [cards, setCards] = useState([])
return (
<div>
<CardList cards={cards} />
</div>
)
}
Cool! We must have a way now to ask GitHub for the details of a single username. We’ll do so using a Form
component, where we manage our own state (username
), and we ask GitHub for information about a user using their public APIs, via Axios:
const Form = props => {
const [username, setUsername] = useState('')
handleSubmit = event => {
event.preventDefault()
axios.get(`https://api.github.com/users/${username}`).then(resp => {
props.onSubmit(resp.data)
setUsername('')
})
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={username}
onChange={event => setUsername(event.target.value)}
placeholder="GitHub username"
required
/>
<button type="submit">Add card</button>
</form>
)
}
When the form is submitted we call the handleSubmit
event, and after the network call we call props.onSubmit
passing the parent (App
) the data we got from GitHub.
We add it to App
, passing a method to add a new card to the list of cards, addNewCard
, as its onSubmit
prop:
const App = () => {
const [cards, setCards] = useState([])
addNewCard = cardInfo => {
setCards(cards.concat(cardInfo))
}
return (
<div>
<Form onSubmit={addNewCard} />
<CardList cards={cards} />
</div>
)
}
Finally we render the app:
ReactDOM.render(<App />, document.getElementById('app'))
Here is the full source code of our little React app:
const { useState } = React
const Card = props => {
return (
<div style={{ margin: '1em' }}>
<img alt="avatar" style={{ width: '70px' }} src={props.avatar_url} />
<div>
<div style={{ fontWeight: 'bold' }}>{props.name}</div>
<div>{props.blog}</div>
</div>
</div>
)
}
const CardList = props => <div>{props.cards.map(card => <Card {...card} />)}</div>
const Form = props => {
const [username, setUsername] = useState('')
handleSubmit = event => {
event.preventDefault()
axios
.get(`https://api.github.com/users/${username}`)
.then(resp => {
props.onSubmit(resp.data)
setUsername('')
})
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={username}
onChange={event => setUsername(event.target.value)}
placeholder="GitHub username"
required
/>
<button type="submit">Add card</button>
</form>
)
}
const App = () => {
const [cards, setCards] = useState([])
addNewCard = cardInfo => {
setCards(cards.concat(cardInfo))
}
return (
<div>
<Form onSubmit={addNewCard} />
<CardList cards={cards} />
</div>
)
}
ReactDOM.render(<App />, document.getElementById('app'))
Check it out on Codepen at https://codepen.io/flaviocopes/pen/oJLyeY
Download my free React Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More react tutorials:
- A React simple app example: fetch GitHub users information via API
- Build a simple counter with React
- VS Code setup for React development
- How to pass props to a child component via React Router
- Create an app with Electron and React
- Tutorial: create a Spreadsheet using React
- The roadmap to learn React
- Learn how to use Redux
- Getting started with JSX
- Styled Components
- Introduction to Redux Saga
- Introduction to React Router
- Introduction to React
- React Components
- The Virtual DOM
- React Events
- The React State
- React Props
- The React Fragment
- The React Context API
- React PropTypes
- React concepts: declarative
- React: How to show a different component on click
- How to loop inside React JSX
- Props vs State in React
- Should you use jQuery or React?
- How much JavaScript you need to know to use React?
- Introduction to Gatsby
- How to reference a DOM element in React
- Unidirectional Data Flow in React
- React Higher Order Components
- React Lifecycle Events
- React Concept: Immutability
- React Concept: Purity
- Introduction to React Hooks
- Introduction to create-react-app
- React Concept: Composition
- React: Presentational vs Container Components
- Code Splitting in React
- Server Side Rendering with React
- How to install React
- CSS in React
- Using SASS in React
- Handling Forms in React
- React StrictMode
- React Portals
- React Render Props
- Testing React components
- How to pass a parameter to event handlers in React
- How to handle errors in React
- How to return multiple elements in JSX
- Conditional rendering in React
- React, how to transfer props to child components
- How to get the value of an input element in React
- How to use the useState React hook
- How to use the useCallback React hook
- How to use the useEffect React hook
- How to use the useMemo React hook
- How to use the useRef React hook
- How to use the useContext React hook
- How to use the useReducer React hook
- How to connect your React app to a backend on the same origin
- The Reach Router Tutorial
- How to use the React Developer Tools
- How to learn React
- How to debug a React application
- How to render HTML in React
- How to fix the `dangerouslySetInnerHTML` did not match error in React
- How I fixed an issue with a React login form state and Browser autofill
- How to configure HTTPS in a React app on localhost
- How to fix the "cannot update a component while rendering a different component" error in React
- Can I use React hooks inside a conditional?
- Using useState with an object: how to update
- How to move around blocks of code with React and Tailwind
- React, focus an item in React when added to the DOM
- React, edit text on doubleclick
- React Router, how to get data from a dynamic route
- React Router, why useLocation and useHistory might return undefined
- The easy-peasy React state management library