It could be a clone post but I did not find any solution for in my case. I have list of an objects:
export default function() {
return [
{name: 'Mark Teer Stegen'},
{name: 'Nelson Semedo'},
{name: 'Gerrard Pique'},
{name: 'Ivan Rakitic'},
{name: 'Sergio Busquets'},
{name: 'Denis Suarez'},
{name: 'Coutinho'},
{name: 'Luis Suarez'},
{name: 'Lionel Messi'},
{name: 'Dembele'},
{name: 'Malcom'}
]
}
I import it to the component, assign to the state and displaying it in the component below.
import React, {Component} from 'react';
import {connect} from 'react-redux';
class Barca extends Component{
constructor(props){
super(props);
this.state = {
players: this.props.players,
player: '' //empty to set as an input
}
}
onChange(e){
this.setState({
player: e.target.value
});
console.log(this.state.player);
}
renderList(){
return this.state.players.map((player) => {
return(
<tr key={player.name}>
<td>{player.name}</td>
</tr>
);
});
}
render(){
return(
<div className="col-sm-6 table-col table-responsive">
<input
type="text"
value={this.state.player}
onChange={this.onChange.bind(this)}
/>
<table className="table table-striped">
<thead>
<tr>
<th className="text-center">
FC Barcelona
</th>
</tr>
</thead>
<tbody>
{this.renderList()}
</tbody>
</table>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
players: state.reducerBarca
};
};
export default connect(mapStateToProps)(Barca);
List looks like that
The problem is that I would like to filter my players list by the value from input. I have done some research here and I have only found filtering in Array, not like I have in Objects list.
What I have done for now:
Thank you all people ! I have removed the players state
constructor(props){
super(props);
this.state = {
//players: this.props.players <-- Stupid thing
player: '' //empty to set as an input
}
}
and rewrite my renderList()
function
return this.props.players.filter(player =>
player.name.toLowerCase().includes(this.state.player.toLowerCase())).map(searchedPlayers => {
return(
<tr key={searchedPlayers.name}>
<td>{searchedPlayers.name}</td>
</tr>
);
})
}
this.state.players.filter(player => player.name.includes(this.state.player))
And if you wanted to then map them instead of just filtering the state...
this.state.players.filter(player =>
player.name.includes(this.state.player)).map(searchedPlayers => {
return(
<tr key={searchedPlayers.name}>
<td>{searchedPlayers.name}</td>
</tr>
);
})
Note you can also render straight from props without setting to state, (to avoid re-renders every-time the user types) by replacing
this.state.players
with
this.props.players
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With