0

I have login component and after user singin i will got data from express server with fetch that will say all okay i want to redirect user to main page.I didn't find anything that i may use with react-router-dom to redirect user. First thing i want to now,is redirect user after he click button, without data check

this is how my Routes

ReactDOM.render(
    <div>
      <div><div className="nav">
         <BrowserRouter>
          <div className="shapka">
            <Link to={linkToLogin} className="login">Войти в профиль</Link>
          </div>
          
          <div className="navItems">
              <Link to='/Rings' className="navItem">Кольца</Link>
              <Link to='/Earrings' className="navItem">Серёжки</Link>
              <Link to='/' className="navItem">Главная страница</Link>
              <Link to='/Bracelets' className="navItem">Браслеты</Link>
              <Link to='/Necklace' className="navItem">Ожерелья</Link>
          </div>
          <Routes>
              <Route path="/" element={<App/>}/>
              <Route path="/Rings" element={<Rings/>}/>
              <Route path="/EarRings" element={<EarRings/>}/>
              <Route path="/bracelets" element={<Bracelets/>}/>
              <Route path="/Necklace" element={<Necklase/>}/>
              <Route path='/Profile' element={<Login/>}/>
              <Route path="Register" element={<Register/>}/>
          </Routes>
          </BrowserRouter>
        </div>
      </div>
    </div>,
  document.getElementById('mainDiv')
);

and this is my component that located in other js file

        login.addEventListener('click',e=>{
            let login = document.getElementById('username')
            let pwd = document.getElementById('password')
            if(login.value !== '' && pwd.value !== ''){
                sendToLogin({login:login.value,pwd:pwd.value})
            }
        })
        
    }


    render(){


        return <div className="main" id="main">
         <div className="registration-cssave">
            <div className="form" >
                <h3 className="text-center">Вход в систему</h3>
                <div className="form-group">
                    <input className="form-control item" type="text" name="login" maxLength="15" id="inputLogin" minLength="4"
                        pattern="^[a-zA-Z0-9_.-]*$" id="username" placeholder="Логин" required />
                </div>
                <div className="form-group">
                    <input className="form-control item" type="password" name="password" minLength="6" id="password"
                        placeholder="Пароль" required/>
                </div>
                <div className="form-group">
                    <button className="btn btn-primary btn-block create-account" type="submit" id="btnEnter">Войти</button>
                </div>
                <div className="toRegister">
                    <a href="/Register" >Регистрация</a>
                </div>
            </div>
        </div>
        </div>
    
    }
}
export default Login
GDTyka
  • 472
  • 3
  • 16
  • What is the button you are trying to add a click handler to and why aren't you using the element's `onClick` handler? You should be able to use the `useNavigate` hook and issue an imperative navigation to a target route from the click handler. Can you update to include complete code? https://stackoverflow.com/help/minimal-reproducible-example – Drew Reese Nov 11 '21 at 19:57
  • 1
    Oh, just saw that your code is a class component. You still need to use the `useNavigate` hook in v6, but you'll have to create your own custom HOC to have the `navigate` function injected as a prop so that login callback can do the navigation. Does this answer your question? https://stackoverflow.com/a/69902006/8690857 – Drew Reese Nov 11 '21 at 20:05

2 Answers2

0

You can use the useHistory hook from react-router-dom

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

function App () {

   const history = useHistory();

   async function logUser (userData) {
      const res = await api.post("yourApi/login",{data});
   
      if(res.status===200){
         history.push("/");
      }
   }

   render(
      // Rendered parts
   )
}

Additionally you can render a hidden Link component with display: "none", attach it to a ref and programmatically click it when the server response is okay. Like this:

const redirectToMain = useRef(null);

async function logUser (userData) {
   const res = await api.post("yourApi/login",{data});
   
   if(res.status===200){
      redirectToMain.current.click()
   }
}

render (
   // *** other parts
   <Link
      to="/"
      ref={redirectToMain}
      style={{display: "none"}}
   />
)
noiseymur
  • 761
  • 2
  • 15
  • 2
    OP is using `react-router-dom` v6 which no longer has an `useHistory` hook, your code won't work. See my above comments and linked answer for explanation. Cheers. – Drew Reese Nov 11 '21 at 20:08
0

for class components, at the first you should make a functional component then use HOC technical to use useNavigate react hook. like this:

withrouter.js:

import {useNavigate} from 'react-router-dom';

export const withRouter = WrappedComponent => props => {
    return (<WrappedComponent {...props} navigate={useNavigate()}/>);
};

then use use it in other class components like this:

export default withRouter(Signin);

and use props for redirect like this:

this.props.navigate('/');
Ali Alizadeh
  • 326
  • 2
  • 6