Ways to transfer a state from the child component to the app component

I have 2 different components that contain sub-components within them. In one of these components, I'm trying to figure out how to transfer the click event from the sub-component to another component so that it can render an entirely new component for me.

I believe using the `useState` hook is the way to go, but I'm not sure where exactly to implement it in my code. I'll provide a snippet below to show what I've done so far, but I'm stuck on how to proceed:

app.jsx

import React, { useState } from 'react';
import './App.css';
import SignIn from './components/sign-in/SignIn';
import SignUpOptions from './components/sign-in/sign-up-select-business-option';

const [signUp, setSignUp] = useState(false);

const App = () => {
    if (signUp) {
        return <SignUpOptions/>
    }
    return <SignIn/>;
};

export default App;

signin.jsx

const SignIn = () => (
    <div style={{display:'flex'}}>
      <div style={{flex:2}}>
        <ImageDiv bg={signin} src = {signin} alt="logo">
          <LogoDiv src={logo} alt="logo" />
        </ImageDiv>
      </div>
      <FormDiv>
        <Input style={{marginTop: `${44}px`}} placeholder="Username" />
        <Input style={{marginTop: `${44}px`}} placeholder="Password" />
        <Button style={{marginTop: `${45}px`}}>Sign in</Button>
        <ForgotPassword>Forgot username or password</ForgotPassword>
        <SignUpParagraph>Don’t have an account? Sign up</SignUpParagraph>
      </FormDiv>
    </div>
)

export default SignIn;

So basically, when a certain action is triggered in the `SignIn` component, I want the `SignUpOptions` component in `app.jsx` to be loaded instead.

Answer №1

Due to the fact that you are a newcomer, I will refrain from providing you with a duplicate link

app.jsx

const [register, setRegister] = useState(false);

const App = () => {
  if (register) {
    return <RegisterOptions/>
  }
    return <Login setRegister={setRegister}/>

};

login.jsx

const Login = (props) => (
<div style={{display:'flex'}}>
  <div style={{flex:2}}>
    <ImageDiv bg={login} src = {login} alt="logo">
      <LogoDiv src={logo} alt="logo" />
    </ImageDiv>
  </div>
 <FormDiv>
    <Input style={{marginTop: `${44  }px`}} placeholder="Username" />
    <Input style={{marginTop: `${44  }px`}} placeholder="Password" />
    <Button style={{marginTop: `${45  }px`}}>Log in</Button>
    <ForgotPassword>Forgot username or password</ForgotPassword>
    <RegisterParagraph setRegister={props.setRegister}>Don’t have an account? Register</RegisterParagraph>
  </FormDiv> 

RegisterParagraph.js

const RegisterParagraph = (props) => (
<div onClick={()=>props.setRegister(true)}>//anything you have in here </div>

Comment if it worked

Answer №2

Even though you have already discovered a solution, I would like to offer an alternative approach.

By utilizing React Context, you can create functions in your index or app.js file and then invoke them within your child components. This is a streamlined method that works effectively, especially when used in conjunction with hooks.

Best regards

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with resetting React Material UI TextField when using the useForm hook reset function

Currently, I am working on a project where I am utilizing React and MUI. Within my forms, I have implemented the useForm hook from react-hook-form. Here is a snippet of how I am using it: React.useEffect(() => { const defaultValues = new Provider(); ...

What is the underlying mechanism of the "makeStyles" function in React Material-UI?

I am struggling to comprehend the inner workings of the code that involves the use of makeStyles(). It seems like every time I encounter this code, I end up mindlessly copying and pasting without truly understanding what is happening behind the scenes. To ...

Creating a sleek animation with JQuery for a dynamic-width div

Here is a snippet from my latest project. Take a look at the demonstrationFIDDLE. In this project, I have created a list with buttons: <a href="#f1" class="bt">1 <div class="show">Computers Networking</div> </a> When you ...

How can you dynamically disable a radio option button using Angular rendering without relying on an ID?

Is there a way to disable the male radio button without using an id, and utilizing angular rendering2? It seems like it's not working for me. I need to make this change only in the form.ts file, without altering the HTML code. form.html <label& ...

Having trouble executing a jQuery function within AJAX-generated code

I may not be very experienced in JavaScript programming, but I am learning and trying my best to improve. Please excuse any errors I make along the way. Currently, I am attempting to use Ajax (not jQuery ajax) to save customer details, which then returns ...

How can I automatically center a Vimeo iframe vertically without having to manually adjust the position?

I'm trying to adjust a popular fluid jQuery script so that it can automatically center a vimeo video vertically, without any black bars. A little horizontal cropping is acceptable. Here is my current code: HTML <div class="container"> < ...

Issue: Unable to authenticate the initial certificate following the configuration of an id_rsa

Upon executing the commands below, I encountered an error while trying to start a nextJS app: ssh-keygen -t rsa -C "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2afbba7afa3abae82a7baa3afb2aea7eca1adaf">[email pr ...

The issue of array sorting, specifically the function(a, b) {return b.value - a.value), is causing some

I am struggling to retrieve data from firebase and sort them according to the field 'overallScore' in descending order. Despite following suggestions like using array.sort(function(a, b) {return b.value - a.value), I have not been successful in s ...

The plugin registration failed for 'html-webpack-plugin-before-html-processing' as the specified hook could not be located

An error occurred: Plugin could not be registered at 'html-webpack-plugin-before-html-processing'. The hook was not found. BREAKING CHANGE: There must be a hook at 'this.hooks'. To create a compatibility layer for this hook, hook into & ...

"Disabling checkbox selection for DataGrid cells/fields in React Material UI - A Step-by-Step

Hello, I've encountered an issue with a checkbox selection and a link within the same cell in a Material UI DataGrid table. The challenge is that when clicking on a cell that contains an external link which redirects to another page, the checkbox a ...

Can anyone guide me on troubleshooting the firebase import error in order to resolve it? The error message I am encountering is "Module not found: Error:

When attempting to import the 'auth' module from my 'firebase.js' file, I encountered an error. I used the code import {auth} from "./firebase", which resulted in the following error message: Error: Unable to locate module &a ...

Guide to sending client-to-client notifications in Angular/Ionic with Firebase Cloud Messaging

I am looking to implement client-client push notifications (not server-to-client). My goal is to send a notification when one user messages another. Is this feasible? How can I achieve this using the structure in the Firebase real-time database? Here is a ...

Tips for displaying a React component with ReactDOM Render

_Header (cshtml) <div id="Help"></div> export default class Help { ReactDOM.render( <Help/>, document.getElementById('Help') ); } Help.js (component) } My objective is to di ...

Include a "remember me" feature in the Stripe form

I am currently working on an exciting project using Angular 6. Within my website, I have decided to integrate the Stripe payment system. However, I would like to incorporate a unique and default "remember me" feature offered by Stripe. <div id="card-e ...

Is it possible to export CSS stylesheets for shadow DOM using @vanilla-extract/css?

I have been exploring the use of @vanilla-extract/css for styling in my React app. The style method in this library exports a className from the *.css.ts file, but I need inline styling to achieve Shadow DOM encapsulation. During my research, I came acros ...

Exploring ways to implement authentication by leveraging Redux state variables

After logging in, I have utilized a state variable in Redux that changes. How can this be used to determine if the user is logged in or not? Upon refreshing the page, it automatically redirects to the login page. if(authError === "") return <R ...

Revise directive following the dynamic addition of elements

My Objective: I aim to utilize directives for creating custom elements and dynamically inserting them into the view at various points in time. The Challenge: Upon dynamically adding custom elements to the view, they appear as raw HTML without the directi ...

I am experiencing an issue where emojis are not displaying properly on Facebook, Instagram, and LinkedIn when I share posts from my

I've developed a unique social media management application that enables users to automatically post on their social profiles using the Facebook, Instagram, and LinkedIn APIs. Everything is functioning well, except for one issue - my Emojis are not di ...

Dynamic content with Socket.io in Node.js

I am attempting to create a scenario where nodejs triggers an event in an irc chat that causes a html page (Running on *:3000) to execute some JavaScript. However, I am facing an issue where the showDiv(); function is not being executed as expected. Curre ...

Having trouble with implementing both filter and infinite scroll simultaneously in an Ionic list?

I've encountered an issue with my ionic hybrid app related to angularjs filters. The code snippet below showcases the problem: <input type="search" placeholder="Search personalities" ng-model="name" ng-change='alert("changed!")&apo ...