0

I have a state with a 4 properties. Initially, all of them will be set to false. But, when I will click the button , the particular one will change to true and it all other values will be displayed. I am trying to use filter method but I am unable to do so.

State:

state = {
    hospitals: [
      { id: 'h1', name: 'Apollo Hospital', city: 'Chennai' },
      { id: 'h2', name: 'Fortis Hospital', city: 'New Delhi'},
      { id: 'h3', name: 'Tata Memorial Hospital', city: 'Mumbai'},
      { id: 'h4', name: 'Lilavati Hospital', city: 'Pune',}
    ],
};
1
  • where are you setting them to false? Commented Jul 28, 2020 at 21:04

1 Answer 1

1

I'm not entirely sure whether I grasped properly the expected behavior.. Are you trying to implement something, like this?

const { useState } = React,
      { render } = ReactDOM,
      rootNode = document.getElementById('root')
      
const data = {
    hospitals: [
      { id: 'h1', name: 'Apollo Hospital', city: 'Chennai' },
      { id: 'h2', name: 'Fortis Hospital', city: 'New Delhi'},
      { id: 'h3', name: 'Tata Memorial Hospital', city: 'Mumbai'},
      { id: 'h4', name: 'Lilavati Hospital', city: 'Pune',}
    ],
}

const App = () => {
  const [filters, setFilters] = useState(
          Object.assign(
            {},
            ...data.hospitals.map(({city}) => ({[city]: false}))
          )
        ),
        onFilter = ({target:{value}}) =>
          setFilters({
            ...filters,
            [value]: !filters[value]
          })
       
   return(
    <div>
      {
        Object.keys(filters).map(button => (
          <input 
            type="button"
            value={button} 
            key={button}
            onClick={onFilter}
            className={filters[button] ? 'activeButton' : ''}
          />
        ))
      }
      <ul>
        {
          data.hospitals.map(({id,name,city}) => 
            (!Object.values(filters).some(Boolean) || filters[city]) && (
            <li key={id}>{name} ({city})</li>
          ))
        }
      </ul>
    </div>
   )    
}

render (
  <App />,
  rootNode
)
.activeButton {
  background-color: orange;
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.