-1

In the following example from docs on useReducer

The state variable text is used in

onChangeText={(text) => {
      dispatch({ type: 'first', value: text })
    }}

But as far as I can see it is not declared anywhere beforehand. Am I missing something?

import React, { useReducer } from 'react'
import { View, Text, TextInput } from 'react-native'

function reducer(state, action) {
  switch (action.type) {
    case 'first':
      return { ...state, first: action.value }
    case 'last':
      return { ...state, last: action.value }
  }
}

export default function App() {
  const [state, dispatch] = useReducer(reducer, { first: '', last: '' })

  return (
    <View>
      <TextInput
        style={{ fontSize: 32 }}
        placeholder="First"
        value={state.first}
        onChangeText={(text) => {
          dispatch({ type: 'first', value: text })
        }}
      />
      <TextInput
        style={{ fontSize: 32 }}
        placeholder="Last"
        value={state.last}
        onChangeText={(text) => {
          dispatch({ type: 'last', value: text })
        }}
      />
      <Text style={{ fontSize: 32 }}>
        Hello {state.first} {state.last}
      </Text>
    </View>
  )
}

I apologize for concerning you if this is something trivial. I am new to this environment..!! This community is wonderful.

1 Answers1

1

'text' is the press event.
Read this:
https://reactnative.dev/docs/view#props
https://reactnative.dev/docs/pressevent

elirand5
  • 231
  • 1
  • 7