Form.js
What I wish to get out of this form is a link like '/search/inputValue/' so from another component I can extract the parameter. What I get instead is just '/search/' without the input value.
import React from 'react';
import { Link } from 'react-router-dom';
class Form extends React.Component {
state = {
searched: ''
}
onSubmit = (e) => {
const keyword = e.target.elements.keyword.value;
this.setState({ searched: keyword });
}
render(){
return (
<form className="form-inline" onSubmit={this.onSubmit}>
<div className="form-group">
<input type="text" className="form-control" name="keyword" placeholder="Image keyword" />
<Link to={ `/search/${this.state.searched}`}>
<button className="btn btn-primary">Search</button>
</Link>
</div>
</form>
);
}
};
export default Form;
I have noticed that the state updates its value after a second submit with the older input value, so the problem might be from here.
This can be checked by removing the Link tag, preventDefault and console log the input value. The first one is blank and the second one is with the previous input value.
My whole app is sorted, I just need to figure how to submit to a link from an input.
Router.js
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import App from '../App';
import SearchPage from './SearchPage';
const Router = () => (
<BrowserRouter>
<Switch>
<Route path="/" component={App} exact />
<Route path="/search/:keyword" component={SearchPage} />
</Switch>
</BrowserRouter>
);
export default Router;