简体   繁体   中英

REACT:Help conditionally rendering btn

I cant get a button to show "shortlist" then change to "remove" when conditionally rendered. It is changing in state from true to false and back to true but the button wont change in the Btn component!

Here is where it is rendered in app:

{filteredApplicants.map((applicant) => {
    return(<div className='applications'> <ul >
      <li  className='applicant-li' key={applicant.id}> <h5>{applicant.name} - {applicant.position}</h5>
        <p></p>
        <Btn onFavorite={() => this.onFavorite(applicant)} shortlist={this.state.showShortlist} />
      </li></ul> </div>
    )
  })}

Here is state and the function in app:

         searchField:'',
          saved:[],
          positions:[],
          showShortlist: true
      }
    }
onFavorite = applicant => {
  const { saved, showShortlist } = this.state; 
  console.log(showShortlist)
  if(this.state.saved.includes(applicant)){
    this.setState({showShortlist:!showShortlist})
  } else
   this.setState({
    saved:[...saved, applicant]})
}

Here is the btn component:

import React,{Component} from 'react';

class Btn extends Component{
    constructor({shortlist}){
        super({shortlist})
    }
    render(){

        const remove = <button>Remove</button> 
        const add = <button>Shortlist</button>  
        console.log(this.props.shortlist)
        return(

            {shortlist:true} ? <button onClick={this.props.onFavorite}>Remove</button>:<button>Shortlist</button>  
        )
    }
}

export default Btn;

You need a correction on your render method, it should be like:

    render() {
      const {shortlist, onFavorite} = this.props;
      return (<button onClick={onFavorite}>{shortlist ? 'Remove' : 'Add Favorite'}</button>);
    }

Also, your onFavorite method should be like:

onFavorite = applicant => {
  const { saved } = this.state; 
  const index = saved.indexOf(applicant);

  if(index === -1) {
   this.setState({
    saved: [...saved, applicant],
   });
  } else {
    saved.splice(index, 1);
    this.setState({saved});
  }
}

And each button on your map should be passing different props:

{filteredApplicants.map((applicant) => {
return (<div className='applications'> <ul>
  <li className='applicant-li' key={applicant.id}> <h5>{applicant.name} - {applicant.position}</h5>
    <p></p>
    <Btn onFavorite={() => this.onFavorite(applicant)} shortlist={this.state.saved.includes(applicant)} />
  </li></ul> </div>
)
})}
{shortlist:true} ?

doesn't mean anything. You're passing this.props.shortlist as a boolean. true:true is not valid anything

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM