Home > Mobile >  How to filter an array on click in react?
How to filter an array on click in react?

Time:10-06

So, basically, I'm making a website where you can search for Minecraft hacked clients. There is a search bar on the website, but you have to search in exact terms (different topic lol). Basically on the click of a button (search button) I then want to filter using the search term, (not automatically as I have it now) I've been searching but cant find a way to do it.

Code ->

import CountUp from 'react-countup';
import { Link } from 'react-router-dom';
import '../App.css';

/*Components ->*/
import Client from '../components/client.js'

function App() {

    const [search, setSearch] = React.useState({
        searchname: ''
    });

    **Array containing client data ->** const [client, setClient] = React.useState([
        { safestatus: 'safe-status-green', safe: 'Safe (Verified)', name: 'Impact', price: 'Free', mcversion: '1.11.2 - 1.16.5', type: 'Injected', compat: 'None (Stand alone client)', desc: 'The Impact client is an advanced utility mod for Minecraft, it is packaged with Baritone and includes a large number of useful mods.', screen: 'https://impactclient.net/', download: 'https://impactclient.net/'},
        { safestatus: 'safe-status-green', safe: 'Safe (Verified)', name: 'Future', price: '15€', mcversion: '1.8.9 - 1.14.4', type: 'Injected', compat: 'None (Stand alone client)', desc: 'Vanilla, OptiFine, Forge and Liteloader support, Easy to use account manager, Auto-reconnect mod.', screen: 'https://www.futureclient.net/', download: 'https://www.futureclient.net/'}
        
    ]);

    const updateSearch = (event) => {
        event.persist();
        setSearch((prev) => ({
            ...prev,
            [event.target.name]: event.target.value
          }));
    };
    
  return (
    <body>
        <div className='header'><Link to='/'>Hacked Hub</Link><div className='header-links'><Link to='/about-us'>About Us</Link> | <Link to='/faq'>FAQ</Link></div></div>
        <div className='counter'><CountUp end={16} duration={0.5}></CountUp> </div>
        <div className='counter-desc'><div className='code'>hacked clients</div> and counting...</div>
        <div className='nxt-tab'>
            <input name='searchname' value={search.searchname} onChange={updateSearch} placeholder='Search'></input>
            <select name='price'>
                <option value='Free'>Free</option>
                <option value='Paid'>Paid</option>
            </select>
            <select name='safe'>
                <option value='Safe'>Safe</option>
                <option value='Probably Safe'>Probably Safe</option>
                <option value='Not Safe'>Not Safe (BE CAREFUL!)</option>
            </select>
            <select name='mcver'>
                <option value='1.8.9'>1.8.9</option>
                <option value='1.12.2'>1.12.2</option>
                <option value='1.16.5'>1.16.5</option>
                <option value='1.17 '>1.17 </option>
            </select>
            <select name='type'>
                <option value='Main'>Injected</option>
                <option value='Side'>Mod</option>
            </select>
            <select name='compatibility'>
                <option value='With Most Other Clients'>With Most Other Clients</option>
                <option value='Stand Alone'>Stand Alone</option>
            </select>
            <div className='client-warning'><div className='safe-status-red'><div className='code'>⚠ WARNING ⚠</div></div> Only download clients you know are <div className='code'>100%</div> safe! If we do find a client that is a <div className='code'>rat / virus / BTC miner</div> we will tag it as <div className='safe-status-red'><div className='code'>UNSAFE IMMEDIATELY</div></div>. The saftey warnings for clients are <div className='code'>MERE RECCOMENDATIONS</div>, please do thorough research before downloading any hacked client that you are not <div className='code'>100%</div> sure is safe. This page is also in <div className='code'>development</div>, meaning features are prone to break! So be careful!!!</div>
            <div className='code'>Sponsored clients</div>
                <h1>None XD</h1>
            <div className='code'>Submitted clients</div>
                {client
                    **Filtering the array then mapping it -> (This i want to do onClick)** .filter((client) => client.name === search.searchname)
                    .map((client, index) => {
                        return (
                            <Client
                                safestatus={client.safestatus}
                                safe={client.safe}
                                name={client.name}
                                price={client.price}
                                mcversion={client.mcversion}
                                type={client.type}
                                compat={client.compat}
                                desc={client.desc}
                                screen={client.screen}
                                download={client.download}
                            />
                        );
                    })}
            </div>
    </body>
  );
}

export default App;

Anyone know how I could do this onClick?

CodePudding user response:

Use two piece of state; one to track the value in your text field and the other to store the search term for filtering. Only set the latter when you click your button

const [ searchValue, setSearchValue ] = React.useState("")
const [ searchTerm, setSearchTerm ] = React.useState("")

const filteredClient = React.useMemo(() => {
  if (searchTerm.length > 0) {
    return client.filter(({ name }) => name === searchTerm)
  }
  return client
}, [ searchTerm, client ])

and in your JSX

<input
  name="searchname"
  placeholder="Search"
  value={searchValue}
  onChange={e => setSearchValue(e.target.value)}
/>

<!-- snip -->

<button
  type="button"
  onClick={() => setSearchTerm(searchValue)}
>Search</button>

<!-- snip -->

{filteredClient.map((client, index) => (
  <Client .../>
))}

CodePudding user response:

All you need is an array filter method like this:

const list=[
        { safestatus: 'safe-status-green', safe: 'Safe (Verified)', name: 'Impact', price: 'Free', mcversion: '1.11.2 - 1.16.5', type: 'Injected', compat: 'None (Stand alone client)', desc: 'The Impact client is an advanced utility mod for Minecraft, it is packaged with Baritone and includes a large number of useful mods.', screen: 'https://impactclient.net/', download: 'https://impactclient.net/'},
        { safestatus: 'safe-status-green', safe: 'Safe (Verified)', name: 'Future', price: '15€', mcversion: '1.8.9 - 1.14.4', type: 'Injected', compat: 'None (Stand alone client)', desc: 'Vanilla, OptiFine, Forge and Liteloader support, Easy to use account manager, Auto-reconnect mod.', screen: 'https://www.futureclient.net/', download: 'https://www.futureclient.net/'}
    ]
let searchTerm="Impact"
list.filter((listItem)=>{ 
     if(listItem.name==searchTerm){
           return <YourReactComponent item={listItem} />
}

})

  • Related