Reputation: 51
I have to create a comments app. I have created a login page where I enter the name and hit the submit button to move to another page where I have to make some comment. I want to use the name which is entered on login page to be used in the Comment Page along with my comment. I want to know how I can send the input name to the other component on hitting submit button and use that name on the Comment page.
My Login page is :
import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import CommentForm from './CommentForm';
class LoginForm extends Component {
state={
username:''
}
handleClick = e =>{
console.log('username',this.state.username);
this.props.history.push('/main');
}
render() {
return (
<div className='text-center'>
<MuiThemeProvider>
<div>
<AppBar title="Login"/>
<TextField
hintText="Enter your Name"
floatingLabelText="Name"
value={this.state.username}
onChange = {(e) => this.setState({username:
e.target.value})}
/>
<br/> <br/>
<RaisedButton label="Submit" primary={true} style={style}
onClick={this.handleClick}/>
</div>
</MuiThemeProvider>
</div>
);
}
}
const style = {
margin: 15,
};
export default LoginForm;
Upvotes: 0
Views: 85
Reputation: 2021
here you can use any use
this.props.router.push({
pathname: '/main',
state: {
username:'parker'
}
})
or
this.props.history.push('/main', { username:this.state.username }))
For rouet.push() please read below
On the page that is navigated to, the current location will be injected into the component whose route matched, so you can access the state using this.props.location.state.
One thing to keep in mind is that there will be no state if a user navigates directly to the page, so you will still need some mechanism to load the data when it does not exist.
Upvotes: 0
Reputation: 15688
There's a couple of ways to do this, but assuming you don't want to download any more libraries, this would be the easiest.
It looks like you're already using react-router-dom
so all you have to do is modify your existing route for /main
like so.
<Route path="/main/:name" component={whateveryourcomponentis}/>
What we did was add a wild-card to the end of that route so you can pass in data.
Then in your event handler just pass in this.state.username
handleClick = e =>{
this.props.history.push(`/main/${this.state.username}`);
}
Now in the component you navigated to, you can access the username by calling
this.props.match.params.name
Where .name
is the wildcard that you passed.
Upvotes: 1