Skip to content

Instantly share code, notes, and snippets.

import React, { useState } from 'react'
import useApp from './useApp'
const App = () => {
const { onSubmit } = useApp()
const [name, setName] = useState('')
const [gender, setGender] = useState('Male')
const onNameChange = (e) => setName(e.target.value)
const onGenderChange = (e) => setGender(e.target.value)
return (
const useApp = () => {
const onSubmit = (friend) => (e) => {
e.preventDefault()
console.log(friend)
}
return {
onSubmit,
}
}
const reducer = (state, action) => {
switch (action.type) {
case 'add-friend':
return {
...state,
friends: [...state.friends, action.friend],
history: [...state.history, state],
}
case 'undo': {
const isEmpty = !state.history.length
import { useReducer } from 'react'
// ... further down inside the custom hook:
const [state, dispatch] = useReducer(reducer, initialState)
const onSubmit = (friend) => (e) => {
e.preventDefault()
if (!friend.name) return
dispatch({ type: 'add-friend', friend })
}
const undo = () => {
dispatch({ type: 'undo' })
}
import { useReducer } from 'react'
const initialState = {
friends: [],
history: [],
}
const reducer = (state, action) => {
switch (action.type) {
case 'add-friend':
const App = () => {
const { onSubmit, friends } = useApp()
const [name, setName] = useState('')
const [gender, setGender] = useState('Male')
const onNameChange = (e) => setName(e.target.value)
const onGenderChange = (e) => setGender(e.target.value)
return (
<div>
<form className="form" onSubmit={onSubmit({ name, gender })}>
// At the top
import female from './images/female.jpg'
import male from './images/male.jpg'
// Somewhere above the App component
const FriendBox = ({ gender, ...props }) => (
<div
className={cx('box', {
'teal-border': gender === 'Male',
'hotpink-border': gender === 'Female',
import React, { useState } from 'react'
import cx from 'classnames'
import female from './images/female.jpg'
import male from './images/male.jpg'
import useApp from './useApp'
const FriendBox = ({ gender, ...props }) => (
<div
className={cx('box', {
'teal-border': gender === 'Male',
.boxes {
margin: 10px 0;
padding: 3px;
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: 1fr;
}
.box {