devmeetings-react-ts-fork
  • Devmeeting React + Typescript
  • Speed dating
  • Typescript
    • It's just JavaScript
    • Basic types
    • Typing objects
    • Typing functions
    • Modules
    • Generics
    • Tasks
  • Hello React
    • Quick look around
    • The first component
    • JSX
    • Tasks
  • Components & Props
    • Small components
    • Passing data to a component
    • Loops in JSX
    • Tasks
  • Stateful components
    • Handling events
    • Components with internal state
    • Talking to a parent component
    • Smart and dumb components
    • Before the break
    • Tasks
  • Side-effects and context
    • Side-effects
    • Prop drilling
    • Using context
    • Tasks
  • What's next
    • Styling
    • Learning component's lifecycle
    • State Management
Powered by GitBook
On this page

Was this helpful?

  1. Stateful components

Talking to a parent component

We've learned earlier that a parent passes data to a child component by props. What about passing data from a child to a parent? The simplest way for child to talk to a parent is to call a function given from that parent:

type CounterProps = { increment: () => void; decrement: () => void; }

const Counter: React.FC<CounterProps> = ({ increment, decrement }) => {
    return (
        <div>
            <button onClick={increment}>+</button>
            <button onClick={decrement}>-</button>
        </div>
    )
}
const App: React.FC = () => {
    const [count, setCount] = useState<number>(0)

    const onIncrement = () => setCount(count + 1)
    const onDecrement = () => setCount(count - 1)

    return (
        <div>
            { count }
            <Counter increment={onIncrement} decrement={onDecrement} />
        </div>
    )
}
PreviousComponents with internal stateNextSmart and dumb components

Last updated 5 years ago

Was this helpful?

Edit talking with parent