Souichi Kitai
Souichi Kitai

Reputation: 45

React useHistory: Hooks can only be called inside the body of a function component

import 'bootstrap/dist/css/bootstrap.min.css';
import React, {Component}from 'react';
import {BrowserRouter, Route, Link} from 'react-router-dom';
import './App.css';

import {Home} from './Home';
import {About} from './About';
import {List} from './List';
import {Button} from 'reactstrap';

const App = () => {
  return(
  <BrowserRouter className = 'App'>
  
  <h1 className = 'App-header'>Welcome to To Do List</h1>

    <div>
      <ul>
        <>
        <Button outline color="secondary" size="sm" block><Link to='/' style={{color: 'black'}} >Home</Link></Button>{' '}
        <Button outline color="info" size="sm" block><Link to='/about' style={{color: 'black'}} >How to use</Link></Button>
        <Button outline color="success" size="sm" block><Link to='/friends'style={{color: 'black'}}>To do list</Link></Button>
        </>
      </ul>

      <hr/>

      <Route exact path = '/' component={Home} />
      <Route path = '/about' component={About} />
      <Route path = '/friends' component={List} />
      
    </div>
  </BrowserRouter>
  )
}



export default App

I am trying to use useHistory from 'react-router'. However, seems like I keep getting this error. Even though I tried to find solutions online, my error does not seem like "Breaking hooks rule" and any other error.

Is there any way to deal with the problem?

I added my App.js as well

Thanks

import React from 'react';
import './App.css';
import { useHistory } from 'react-router';
import {Button} from 'reactstrap';

const List = () => {

    const history = useHistory({});

    const handleOnClickLogin = () => {
        alert('login clicked');
        history.push('/');
      };

    return(
        <div className="list-component">
            <h2>To do list</h2>
            <Button color = "primary"
                    onClick={handleOnClickLogin}>
                Add
            </Button>
        </div>
    )
}

export default List;

Upvotes: 2

Views: 2057

Answers (2)

jpm
jpm

Reputation: 107

If importing from the "react-router-dom" isn't working try running the npm install

$ npm install --save react-router-dom

Upvotes: -1

Matheus Martins
Matheus Martins

Reputation: 171

You are importing useHistory from react-router, but this is a function from react-router-dom, so try to do the import like

import { useHistory } from "react-router-dom";

Of course you need to install this package, if it doesn't exist in your package.json file. Let me know if it works.

Upvotes: 3

Related Questions