react button onClick redirect page
Don't use a button as a link. Instead, use a link styled as a button.
<Link to="/signup" className="btn btn-primary">Sign up</Link>
Button onClick() page redirect in ReactJS
SOLUTION 1: Without Routing, you can achieve it using multi-entry in webpack
and by creating a separate page in your bundle using HTMLWebpackPlugin
entry: {
resume: require.resolve('./path/to/Resume.js'),,
},
output: {
filename: '[name].[contenthash:8].js'
},
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(
{
filename: 'resume/index.html',
inject: true,
template: 'SOME_HTML_TEMPLATE,
}
)
),
]
SOLUTION 2 With routing
It is much easier to implement
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, useHistory } from 'react-router-dom';
//css imports
import './App.css';
import './SplashPage/splashpage.css';
//File Imports
import Resume from "./Resume/resume.js";
//Component Import
import Button from '@material-ui/core/Button';
function App() {
const history = useHistory()
return (
<div className="App">
{ <div id="cf">
<Button onClick={() => history.push('resume')}>
CLICK ME
</Button>
</div> }
</div>
);
}
const Main = () => (
<BrowserRouter>
<Switch>
<Route path="/resume" component={Resume} />
<Route path="/" component={App} />
</Switch>
</BrowserRouter>
)
export default Main;
How to redirect to another page on button click in Reactjs
Basically React does not have "pages". The idea is more to "show" or "hide" components, this gives the user a page/view impression.
The easiest way to achieve routing in React is to use a declarative router library like react router especially for more complex apps.
Here is an example without react router to understand the basic concept:
const ViewOne = ({onClick}) => ( <div> View 1 <br /> <button onClick={() => onClick("view2")}>Go to view 2</button> </div>);
const ViewTwo = ({onClick}) => ( <div> View 2 <br /> <button onClick={() => onClick("view1")}>Go to view 1</button> </div>);
const App = () => { const [currentView, setCurrentView] = React.useState("view1"); return ( <div> { currentView === "view1" ? <ViewOne onClick={page => setCurrentView(page)} /> : <ViewTwo onClick={page => setCurrentView(page)} /> } </div> );};
const domContainer = document.querySelector('#my-app');ReactDOM.render(<App />, domContainer);
<div id="my-app"></div>
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
Redirect to another page in reactJS onClick
You don't need to use the Link component in this example. Try using the history prop (props.history.push('/')) See the below examples, the last one should apply to you:
In your App.js router:
<Switch>
<Route path="/auth" component={Auth} />
<Route path="/errorpage" component={ErrorPage} />
<Route path="/" exact component={HomeScreen} />
<Redirect to='/' />
</Switch>
On the page where you want to redirect:
import React, { useState } from 'react'
const Auth = props => {
const [form, setForm] = useState({
data: {
email: '',
password: ''
}
})
const authHandler = async (event) => {
event.preventDefault()
try {
// await dispatch(action) // dispatch to redux or send a fetch
props.history.push('/') // redirects if no errors
} catch (err) {
props.history.push('/errorpage') // redirects if an error
}
}
const inputChangedHandler = e => {
setForm({
...form,
data: {
...form.data,
[e.target.id]: e.target.value
}
})
}
return (
<div>
<form onSubmit={authHandler}>
<input id='email' type='email' value={form.data.email} onChange={inputChangedHandler} />
<input id='password' type='password' value={form.data.password} onChange={inputChangedHandler} />
<button type='submit'>Login</button>
</form>
</div>
)
}
export default Auth
In your case try the below if the page is on the route stack the history prop will be available or you will have to use withRouter or useHistory hook to get access to the history prop.
const clickHandler = () => {
try {
// await dispatch(action)
props.history.push('/') // redirects
} catch (err) {
props.history.push('/errorpage') // redirects
}
}
return (<button type='button' onClick={clickHandler}>Click Me</button)
React - redirecting to full url and not relative url
So in this case , you are not needing the power of react router .
Keep it simple and only use html a tag
<a href="your link here">Take the survey</a>
Related Topics
How to Prevent Form to Reload Page After Onsubmit
Hierarchical Json from Flat With Parent Id
How to Render a Collection of Children Using Array
Html Input File Selection Event Not Firing Upon Selecting the Same File
Javascript Regex - No White Space At Beginning + Allow Space in the Middle
Convert 12-Hour Hh:Mm Am/Pm to 24-Hour Hh:Mm
Transforming Null into Empty String in JavaScript
Pass Parameter from Input to Onclick Method
How to Allow Only English Letters in Input Fields
Move Items in Ul Li Up and Down
Fetch - Missing Boundary in Multipart/Form-Data Post
Typeerror: Data.Foreach Is Not a Function
How to Reload the Page Without the Query Parameters
Image Resizing Client-Side With JavaScript Before Upload to the Server
React - How to Add Dynamic Key/Value Pair to an Object