How do you pass state variables between two separate functional components in React Native?

Asked
Active3 hr before
Viewed126 times

10 Answers

variablesseparatefunctionalcomponentsnativestatereact
90%

You can pass state variables between two functional components using props. You can declare state variable in your PassVar like:,and then pass these to RecieveVar() by rendering receivevar inside your Passvar function and then passing these values as params like:,Making statements based on opinion; back them up with references or personal experience.

You can pass state variables between two functional components using props. You can declare state variable in your PassVar like:

const [pass1, setPass1] = useState("")
const [pass2, setPass2] = useState("")
const [pass3, setPass3] = useState("")
load more v
88%

So let's say you have it like this:

errors: [],
   onChange: false,
   pristine: true,
   touched: false,
   value,

In the parent component, to make the Submit Button on the form enabled, we can also have a side effect that will update the overall state of the form. Something like this:

useEffect(() => {
   const isValid = !fieldOne.onChange &&
      fieldOne.errors.length === 0 &&
      fieldOne.value.length !== 0 &&
      !fieldTwo.onChange &&
      fieldTwo.errors.length === 0 &&
      fieldTwo.value.length !== 0 &&
      ...;
   setIsFormValid(isValid);
}, [fieldOne, fieldTwo, ...]);

Based on the CodeSandbox that you provided, here's what you can do to make this work:

import ...

const useStyles = makeStyles(theme => ({ ... }));

const Apptest = props => {

  const classes = useStyles();
  const [isInvalid, setIsInvalid] = useState(true);

  const handleStateChange = updatedState => {
    console.log("updatedState: ", updatedState);
    updatedState.errors.length === 0 ? setIsInvalid(false) : setIsInvalid(true);
  };

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <div className={classes.mainBox}>
          <form className={classes.form} noValidate>
            <Grid container spacing={2}>
              <EmailTextField onStateChange={handleStateChange} />
            </Grid>
            <Button
              variant="contained"
              color="primary"
              disabled={isInvalid}
              className={classes.button}
            >
              Submit
            </Button>
          </form>
        </div>
      </div>
    </Container>
  );
};

export default Apptest;

And in the EmailTextField component:

import React, { useState } from "react";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";

export const EmailTextField = props => {
  const { onStateChange } = props;
  const [state, setState] = useState({
    errors: [],
    onChange: false,
    pristine: true,
    touched: false,
    value: null
  });
  const helperText = "Email address will be used as your username.";

  const handleBlur = event => {
    // Email Validation logic
    const matches = event.target.value.match(
      `[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,3}`
    );
    if (matches) {
      const updatedState = {
        ...state,
        touched: true,
        value: event.target.value,
        errors: []
      };
      setState(updatedState);
      onStateChange(updatedState);
    } else {
      const updatedState = {
        ...state,
        touched: true,
        value: event.target.value,
        errors: ["Please enter a valid email"]
      };
      setState(updatedState);
      onStateChange(updatedState);
    }
  };

  return (
    <Grid item xs={12}>
      <TextField
        variant="outlined"
        required
        fullWidth
        id="email"
        label="email address"
        error={state.errors.length > 0}
        helperText={state.errors.length > 0 ? state.errors[0] : helperText}
        name="email"
        autoComplete="email"
        margin="dense"
        onBlur={handleBlur}
      />
    </Grid>
  );
};

export default EmailTextField;
load more v
72%

Send the callback function to the child1.js as a prop.,In the Parent.js, set a callback function to take in the parameter that you have accessed from the child., From Child to Parent Using Callbacks

1 App
2└── Parent
3├── Child1
4└── Child2
load more v
65%

To pass the state into another component, you can pass it as a prop.,Then, inside <ExampleComponent />, you can access the data as this.props.data.,To update the state in a parent component, you have to pass the data into the callback prop. Instead of giving the data or state into the callback prop, you can send it directly to an external method to complete a specific task. In this guide, you'll learn how to submit a component's state to an external method.

1class ParentComponent extends Component {
2    state = {
3        // ..
4    }
5    render() {
6        return <ExampleComponent data={this.state}>
7    }
8}
load more v
75%

First, you'll need to create two components, one parent and one child.,First, you need to create a function in the parent component called  childToParent and an empty state named data.,Next, you'll import the child component in the parent component and return it.

import React from 'react'

export default function Parent() {
  return (
    <div>
      
    </div>
  )
}
load more v
40%

For functional components:,It is important to remember that props, passed in as function arguments from the component owner are also part of the component state. A functional component will refresh any time it receives new props (means, its old and new props fail referential equality).,props are part of the component state passed in externally from the component’s container.

useState() hook allows you create and mange a state variable that can be a simple JavaScript primitive or an object. Typically this is how you would do it.

const [isAuthenticated, setIsAuthenticated] = useState(false)

useReducer() is used when you’d rather modify state via reducers and actions. An “actions up, data down” approach is recommended for managing complex state. This way, instead of sprinkling your state mutation logic throughout your component/container, it is tucked away inside a reducer. Here is a useReducer() example from the React site:

const initialState = { count: 0 };const reducer = (state, action) => {  switch (action.type) {    case "increment":      return { count: state.count + 1 };    case "decrement":      return { count: state.count - 1 };    default:      throw new Error();  }};const increment = () => ({ type: "increment" });const decrement = () => ({ type: "decrement" });function Counter() {  const [state, dispatch] = useReducer(reducer, initialState);  return (    <>      Count: {state.count}      <button onClick={() => dispatch(increment())}>+</button>      <button onClick={() => dispatch(decrement())}>-</button>    </>  );}

Outside the legacy use of refs for hooking on to the DOM tree, use useRef() to keep a mutable value inside your functional component. Very similar to instance fields in classes. Here is the usage:

const myPromise = useRef();
const onClick = () => {
   myPromise.current = fetch('/myapi');
}
load more v
22%

Please be noted that the App.js is going to be work as the Root component to all and the Parent component has been called inside it.,Then I created a folder called ‘components’ under the /src and created three components called Parent, Child1, and Child2.,Child to Parent data passing is kind of a confusing task. First, we have to create a callback function in the Parent which takes the data to send from the Child1 component.

In order to explain things in a more practical approach, I have created a sample React app by running the following command as usual.

npx create - react - app sample_app
load more v
60%

Line 1: We import the useState Hook from React. It lets us keep local state in a function component.,We’ll start learning about Hooks by comparing this code to an equivalent class example.,Our new example starts by importing the useState Hook from React:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
load more v
48%

Core Components and Native Components,Class components tend to be a bit more verbose than function components.,And as with function components, you can export your class component:

import React from 'react';
import {
   Text
} from 'react-native';
load more v
23%

Step 2: Pass the state and the callback function as props to all children inside the Provider Component.,Step 1: Define a callback function that takes in a parameter which we consider having accessed from the child in the Parent.jsStep 2: Also, send the defined callback function as a props to the Child1.js,Step 3: In Child1.js send the data using this.props.callback(dataToParent)

Let us consider our directory structure to be such that the Parent Component renders child components in the Application.

App└── Parent├── Child1└── Child2
load more v

Other "variables-separate" queries related to "How do you pass state variables between two separate functional components in React Native?"