简体   繁体   中英

ReactJs: need to change Card into another card onClick

here is my goal: There is a "Newuser" button in Login card and it will be clicked, the card will be changed into Register. Login card will be gone. All i have done in material-UI.

my codein codesand

when i click on the button it shows error. if i make this button outside the card i can use if-else condition to show the desired card. but i should keep the button inside the Login form.

while i press the Newuser button, it is saying to use the children array. how can i solve that? thanx in advance

You could pass a function from your parent to your child as a prop, which will setState a boolean to change the displayed card. This way the button stay in your child.

Since you have two cards and you want to switch between them - you need someone to handle which of them to show (it will probably be the container of them).

You can use a state to control which card to show, and based on that state to switch between them:

const [isLogin, setIsLogin] = useState(true);
const handleRegister = () => {
    setIsLogin(false);
}

And inside the login card - when you click on the "register" button just call the handleRegister function.

Your login card will need to get the handleRegister function in order to call it while the button inside is being pressed:

<Login user={user} setUser={setUser} handleRegister={handleRegister} />

And you will need to decide which element to show (the login or the register) based on the value of the isLogin variable:

{isLogin ? <Login user={user} setUser={setUser} handleRegister={handleRegister} /> : <Register />}

Here is a working example: https://codesandbox.io/s/happy-moore-8miyc?file=/src/Login.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM