react preventDefault code example

Example 1: js preventdefault

function(event) {
  event.preventDefault();
}

Example 2: preventdefault

e.preventDefault();

Example 3: prevent default react

import React from 'react';
 
const initialList = [
  'Learn React',
  'Learn Firebase',
  'Learn GraphQL',
];
 
const ListWithAddItem = () => {
  const [value, setValue] = React.useState('');
  const [list, setList] = React.useState(initialList);
 
  const handleChange = event => {
    setValue(event.target.value);
  };
 
  const handleSubmit = event => {
    if (value) {
      setList(list.concat(value));
    }
 
    setValue('');
 
    event.preventDefault();
  };
 
  return (
    <div>
      <ul>
        {list.map(item => (
          <li key={item}>{item}</li>
        ))}
      </ul>
 
      <form onSubmit={handleSubmit}>
        <input type="text" value={value} onChange={handleChange} />
        <button type="submit">Add Item</button>
      </form>
    </div>
  );
};
 
export default ListWithAddItem;

Example 4: react button onclick

import React, { Component } from 'react';

class App extends Component {
  
  constructor(props) {
    super(props);
    this.sayHello = this.sayHello.bind(this);
  }

  sayHello() {
    alert('Hello!');
  }
  
  return (
    <button onClick={this.sayHello}>
      Click me!
    </button>
  );
}

export default App;

Tags:

Html Example