john
john

Reputation: 1389

Prevent the page from refreshin when click a button

I have an navbar with React Redux and an navbar. I am trying to add an robot to my list and it appears after when i click the button add robot the page starts refreshing and my added robots are disappering. How can i stop the refreshing on my page. I have tried with e.preventDefault but it is not working!

import React from 'react';

const AddRobot = ({
    name,
    nameChange,
    addToList
}) => {
    const emailInput = React.useRef();
    const nameInput = React.useRef();
    const userInput = React.useRef();


    const clearInputs = () => {
        emailInput.current.value = "";
        nameInput.current.value = "";
        userInput.current.value = "";
    };

    const fixloading = (e) => {
        e.preventDefault();
    };


    return ( <
        div >
        <
        h1 > Add Robot By Name < /h1>


        <
        input className = 'pa2 ba b--green bg-lightest-blue'
        placeholder = 'Add Name'
        value = {
            name
        }
        onChange = {
            nameChange
        }
        ref = {
            nameInput
        }
        />

        <
        input className = 'pa2 ba b--green bg-lightest-blue'
        placeholder = 'Add Username'
        ///value={username}
        ///onChange={username}
        ref = {
            userInput
        }
        />

        <
        input className = 'pa2 ba b--green bg-lightest-blue'
        name = "email"
        placeholder = 'Add Email'
        ///value={email}
        ///onChange={handleEmail}
        ref = {
            emailInput
        }

        />

        <
        a className = "f50 link dim ph3 pv2 mb2 dib white bg-dark-green ma2"
        href = "addRobo"
        onClick = {
            addToList
        } >
        Add Robot <
        /a>

        <
        a className = "f50 link dim ph3 pv2 mb2 dib white bg-dark-green ma1"
        href = "#0"
        onClick = {
            clearInputs
        } >
        Reset Inputs <
        /a>


        <
        /div>
    );
}


export default AddRobot;

Upvotes: 0

Views: 229

Answers (2)

ROOT
ROOT

Reputation: 11622

Just change this

<a className="f50 link dim ph3 pv2 mb2 dib white bg-dark-green ma2" href="addRobo" onClick={addToList}>Add Robot </a>

to a <span> tag or you can keep it and place # in href attribute like this href="#addRobo".

Upvotes: 0

Josh Kelly
Josh Kelly

Reputation: 978

If the element is not a link, <a> is the wrong html tag for what you need.

use <button type="button" onClick={myFunc}>Button</button> instead so it will act as expected. You can style the button element to make it look the same way as an anchor.

Upvotes: 1

Related Questions