1
I would like to know how to create a search system inside the React having an input and another search button, preferably using React-router if you have how to do it.
In particular I’m trying to use the tag Link, but it only works the first time, in the others it changes the url, but the Route tag remains the same, apparently not updating the Route.
-main
import React, {Component} from 'react'
import './style.css'
import Postings from './pages/Postings/index'
import Search from './pages/Search/index'
import {BrowserRouter, Route, Switch, Link} from 'react-router-dom'
import CreatePost from './pages/CreatePost'
export default class Main extends Component {
state = {
userId: '',
}
render() {
const {userId} = this.state
return (
<main id='main'>
<BrowserRouter>
<div id='subMenu'>
<h2>Busque uma postagem através do id de usuário de quem publicou</h2>
<input id='search' className='search' placeholder='ID de usuário' value={userId} onChange={(e) => this.setState({userId: e.target.value})}></input>
<Link className='searchStart' to={userId == '' ? '/' : `/posts/userId/${userId}`}>Pesquisar</Link>
<hr />
<h2>Crie uma nova postagem agora, apenas clique no botão abaixo e preencha o formulario</h2>
<Link className='createPosting' to={`/posts/create`}>Criar nova postagem</Link>
</div>
<Switch>
<Route exact path='/' component={Postings} />
<Route exact path='/posts/userId/:userId' component={Search} />
<Route exact path='/posts/create' component={CreatePost} />
</Switch>
</BrowserRouter>
</main>
)
}
}
-research component
import React, {Component} from 'react'
import './style.css'
import api from '../../../../service/api'
import imgDelete from '../../../../img/delete.png'
export default class Postings extends Component {
constructor(props) {
super(props)
}
state = {
postings: [],
}
componentDidMount() {
this.loadPostings()
}
loadPostings = async () => {
const response = await api.get(`/posts?userId=${this.props.match.params.userId}`)
this.setState({postings: response.data})
}
deletePost = (post) => {
api.delete(`/posts/${post.id}`)
alert(`Post foi deletado (simulação) - Post ID: ${post.id} / User ID: ${post.userId}`)
}
render() {
const {postings} = this.state
return (
<div className='postings'>
{
postings.map(post => {
return (
<div key={post.id} className='post'>
<img className='delete' onClick={(e) => this.deletePost(post)} src={imgDelete} />
<h3 className='userId'>ID de usuário: {post.userId}</h3>
<h2 className='title'>{post.title}</h2>
<hr />
<p className='body'>{post.body}</p>
</div>
)
})
}
</div>
)
}
}
As I said, I would just like to know how I do a search system, similar to the image below, I am using the React-router because I am still a beginner in React and is what I currently know, but if there is another way I am also interested.