Home > Blockchain >  Next.js onChange is affecting my onClick how do I seperate the two
Next.js onChange is affecting my onClick how do I seperate the two

Time:06-24

When I run the code the buttons don't work unless I take out onChange. I can add () to the end of my functions inside the on click but that makes them run on every key stroke. How do I fix this. It wont't let me post my question without more text so I am going to add some dummy text to post.

import React, { useState } from "react";


export default function Username(props) {
        const [userName, setUsername] = useState('');

        let userToken
        const address = props.address;

        function handleChange(event) {
            setUsername(event.target.value);
        }


        function loginAccount() {
            console.log('account created');
        }

        function createAccount() {
            console.log('logged in');
        }

        function hi(){
            console.log('hi');
        }

        while (userToken == null)
            return (
                <>
                    <div>
                        <p className = "account-Info" >address: {address}</p>
                    </div>
                    <div id="form">
                        <h2 className='user-Create' > Username </h2>
                        <form id='set-User'>
                        <input id='username' className="user-Create" type='text' value={userName} onChange={handleChange} 
                            required minLength='3' maxLength='30' pattern="[a-zA-Z0-9_] " title='only letters, numbers, and underscores.'/>
                            <button className='user-Create' onClick={loginAccount}>Create Account</button>
                            <button className='user-Create' onClick={createAccount}>Login</button>
                            <button className='user-Create' onClick={hi}>hi</button>
                        </form>
                    </div>
                </>
        );

        while (userToken)
            return(
                <p>hello</p>
                );
}

CodePudding user response:

Set type="button" for each button inside your form

<button className='user-Create' type="button" onClick={loginAccount}>Create Account</button>
<button className='user-Create' type="button" onClick={createAccount}>Login</button>
<button className='user-Create' type="button" onClick={hi}>hi</button>

CodePudding user response:

format like this

const FunctionName = (e) =>  {
            console.log('account created');
     

  • Related