DEV Community

Cover image for Updating State of Parent from Child component in React Native
Ashok Naik
Ashok Naik

Posted on

Updating State of Parent from Child component in React Native

Components are basic building blocks of a Web App. Every Popular Javascript Frameworks nowadays follow the Components paradigm which helps in code reuse-ability and abstraction of a feature.

This blogs covers the communication of state between Parent and child component with the help of a Search Screen Example.

In the following Example

  • SearchScreen is the Parent Component.
  • SearchBar is the Child Component.

Lets start with SearchScreen.js

import React, { useState } from "react";
import { Text, StyleSheet, View } from "react-native";
import SearchBar from "../components/SearchBar";//Importing Child Component
const SearchScreen = () => {
  //Setting up the State Variables
  const [term, setTerm] = useState("");

  return (
    <View>
      {/* Passing the State variable from SearchScreen to SearchBar */}
      <SearchBar
        term={term}
        onChangeTerm={(newTerm) => {
          setTerm(newTerm);
        }}
      />
      <Text> The Search Term Entered: {term}</Text>
    </View>
  );
};

const styles = StyleSheet.create({});

export default SearchScreen;
Enter fullscreen mode Exit fullscreen mode

Within the SearchScreen component [term, setTerm] are state variables which are passed as props to the child component SearchBar.

SearchBar.js

import React from "react";
import { TextInput, StyleSheet, View } from "react-native";
import { Feather } from "@expo/vector-icons";

const SearchBar = ({term,onChangeTerm}) => {
  return (
    <View style={styles.background}>
      <Feather name="search" style={styles.iconStyle} />
      <TextInput
        autoCapitalize="none"
        autoCorrect={false}
        style={styles.inputStyle}
        placeholder="Search"
        value={term}
        onChangeText={onChangeTerm}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  background: {
    marginTop: 10,
    backgroundColor: "#909090",
    marginHorizontal: 15,
    height: 50,
    borderRadius: 10,
    flexDirection: "row",
  },
  inputStyle: {
    flex: 1,
    fontSize: 18,
  },
  iconStyle: {
    fontSize: 35,
    marginHorizontal: 15,
    alignSelf: "center",
  },
});

export default SearchBar;

Enter fullscreen mode Exit fullscreen mode

Within the SearchBar Component the {term,onChangeTerm} props passed from the parent are directly accessed through Destructing the props Object.

TextInput element where the user enters the Search Term, value attribute on TextInput element contains the text entered by the user which is mapped to the state variable term and onChangeText event reads the user input and calls the onChangeTerm method.

The end result would be like

Alt Text

Thats All Folks 😀

Thank you for your time.

Top comments (1)

Collapse
 
ashermiti profile image
Asher Mitilinakis

Very helpful, thanks!