📄

Managing State and Text Inputs in React

Sep 1, 2024

Lecture Notes on Using State and Text Inputs in React

Introduction to State with useState Hook

  • State management within React components.
  • Example of state created using useState hook.

Adding a Text Input Field

  • New component: TextInput.
  • Import TextInput at the top of the component.
  • Remove unnecessary elements (e.g., button component).

Initializing State

  • Create two pieces of state:
    • name and setName initialized to "Sean".
    • age and setAge initialized to 30.
  • Output initial states:
    • Name: Sean
    • Age: 30

Creating Input Fields

  • Add labels and text input fields for name and age.
  • Use TextInput for both fields.
  • Create styles for input field:
    • Border width: 1px
    • Border color: #777 (deep gray)
    • Padding: 8px
    • Margin: 10px
    • Width: 200px

Placeholder Text

  • Add placeholder prop for user guidance:
    • Example for name: "e.g., John Doe".
  • Placeholder appears in faint gray and disappears upon typing.

Handling Input Changes

  • Use onChangeText prop to listen for text changes in the input field.
  • Update state using setName with the current value typed by the user.
  • Demonstration: Changes in input field reflect in state immediately.

Second Input Field for Age

  • Repeat process for age input field:
    • Change label to "Enter Age"
    • Change placeholder to "e.g., 99"
  • Update state using setAge with the value from age input field.

Real-Time Updates

  • Demonstrate real-time updates in the output as user types in input fields.
  • Example: Typing "Mario" for name and "25" for age updates displayed values.

Additional Text Input Props

  • multiline prop allows for multiple lines of text input.
  • Example: When enabled, pressing 'enter' creates a new line in the text input.
  • keyboardType prop adjusts keyboard layout:
    • Set to "numeric" for age input to display numeric keyboard.

Conclusion

  • Summary of tracking user input with state updates.
  • Mention of future topics: Working with lists of data.