Home > Software engineering >  Setting Selected State to Mapped Components
Setting Selected State to Mapped Components

Time:06-09

I have a mapped component which iterates through API data. It passes props to each one and therefore each card looks different. See example below.

https://gyazo.com/39b8bdc4842e5b45a8ccc3f7ef3490b0

With the following, I would like to achieve two goals:

When the component is selected, it uses state to STAY SELECTED, and changes the colour as such to lets say blue for that selected component.

I hope this makes sense. How do I index a list as such and ensure the colour and state remains active based on this selection?

See below.

The level above, I map the following cards using these props.

                  {
                    jobs.length > 0 && 
                    jobs.map(
                      (job) => 
                      <JobCard key={job.id} job={job}
                      />)
                  }

I am then using the following code for my components:

const JobCard = ({ job }) => {

  const responseAdjusted = job.category.label
  const responseArray = responseAdjusted.split(" ")[0]

  return (

      <CardContainer>
        <CardPrimary>
          <CardHeader>
            <CardHeaderTopRow>
              <Typography variant = "cardheader1">
                {job.title}
              </Typography>
              <HeartDiv>
                <IconButton color={open ? "error" : "buttoncol"} sx={{ boxShadow: 3}} fontSize ="2px" size="small" fontSize="inherit">
                  <FavoriteIcon fontSize="inherit"
                    onClick={()=> setOpen(prevOpen => !prevOpen)}/>
                </IconButton>
              </HeartDiv>

            </CardHeaderTopRow>
            <Typography variant = "subtitle4" color="text.secondary">
              {job.company.display_name}
            </Typography>
          </CardHeader>

          <CardSecondary>
          </CardSecondary>
        </CardPrimary>
      </CardContainer>
  )
}

CodePudding user response:

You can attach a handler on the <CardPrimary> component by passing a function to the onClick event. That way whenever you click anywhere on the card div, the function will be triggered.

const [isSelected, setIsSelected] = useState(false);

<CardPrimary onClick={() => setIsSelected(true)} className={isSelected ? "css-class-to-highlight-div" : undefined>
  ....
</CardPrimary>

CodePudding user response:

If I'm understanding what you're asking for, which I believe is to have your component be highlighted when it is clicked, then you need to modify the 'CardContainer' component to render with an 'onClick' parameter.

Example:

function CardContainer(props) {
    const cssClass = 'highlighted';
    const my_id = props.id || 'need_an_id';

    var clearExistingHighlight = () => [...document.getElementByClassName(cssClass)].forEach((elem)=>elem.classList.remove(cssClass));

    var isHighlighted = () => document.getElementById(my_id).classList.contains(cssClass);

    var setHighlighted = (e) => {
         clearExistingHighlight();
         e.target.classList.add(cssClass);
    }

    return (
        <div id={my_id} onClick={setHighlighted}>Cheeseburger fry</div>
    )

} 

If you don't want the highlight to disappear, you can get rid of the clearExistingHighlight function. Or if you want it to toggle, I recommend a modification of @sid's answer:

const {useState} = React;
function CardContainer(props) {
    const [isSelected, setIsSelected] = useState(false);

    <div onClick={() => setIsSelected(!isSelected)} className={isSelected ? "highlighted" : undefined>
}

style.css:

.highlighted {
    background-color: 'orange';
}

You can do all of this without any react hook and rely instead on CSS classes. You can use the 'isHighlighted' method to determine if a given component is highlighted or not.

  • Related