I just wanna create a function that returns "login"
if I clicked on login div
and the same with signup.
But my code always returns the else
condition even when clicking on the div
which is supposed to change the parameter value.
const Join = () => {
const form = (state) => {
if (state == 'login') {
return "login"
} else if (state == 'logup') {
return "logup"
} else {
return "external-box"
}
};
return (
<div className='Join'>
<div className={form()}>
<div className='signin-section' onClick={() => form('login')}>Sign in</div>
<div className='signup-section'onClick={() => form('logup')}>Sign up</div>
<div className='loginfrm'>login</div>
<div className='logupfrm'>logup</div>
</div>
</div>
)
}
ReactDOM.render(<Join />, document.getElementById("root"));
<div id=root></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
CodePudding user response:
It is not possible to catch the value returned by the onClick callback. You can use useState
to declare an initial state and track changes to describe which section should be displayed. Then in the JSX part, you can use this state variable to check whether one form or the other needs to be displayed.
You can see a working example here
import { useState } from "react";
export default function App() {
const [visibleSection, setVisibleSection] = useState("login");
const form = () => {
if (visibleSection === "login") {
return "login";
} else if (visibleSection === "signup") {
return "signup";
} else {
return "external-box";
}
};
return (
<div className="Join">
<div className={form()}>
<div
className="signin-section"
onClick={() => setVisibleSection("login")}
>
Sign in
</div>
<div
className="signup-section"
onClick={() => setVisibleSection("signup")}
>
Sign up
</div>
<br />
{visibleSection === "login" && <div className="loginfrm">login</div>}
{visibleSection === "signup" && <div className="logupfrm">signup</div>}
</div>
</div>
);
}
CodePudding user response:
No, it does not return else part.
const Join = () => {
const form = (state) => {
if (state == 'login') {
return "login"
} else if (state == 'logup') {
return "logup"
} else {
return "external-box"
}
};
return (
<div className='Join'>
<div className={form()}>
<div className='signin-section' onClick={() => alert(form('login'))}>Sign in</div>
<div className='signup-section'onClick={() => alert(form('logup'))}>Sign up</div>
<div className='loginfrm'>login</div>
<div className='logupfrm'>logup</div>
</div>
</div>
)
}
ReactDOM.render(<Join />, document.getElementById("root"));
<div id=root></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>