-1

I have a dropdown searchbox that I want to use to display results and I have a card component that I want to display when the dropdown value matches the value of the user the card component is for.

I have retrieved the state of the user from props and compared this with the state of the dropdown to create the function onSearchSubmit to display the card component 'ProfileCard'.

When testing the onSearchSubmit function using console.log, the if statement is true however the ProfileCard component does not display. There are no errors, I just can't see my component being displayed.

Any help will be greatly appreciated. This is my first question on here so if there is not enough information I will try and help as much as I can.

Please see code below. (I have omitted sections of the code I don't think is related to this section).

onSearchSubmit = () => {
    if (this.state.selectedCategory === this.props.category) {
        console.log('it works')
        return ( <ProfileCard/> );
    } else {
        console.log('not working')
    }
}

render() {
    return (<div>
        <button onClick = {
            this.onSearchSubmit
        }> Search</button> 
        </div>
    )
}

Thanks,

John

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
John Mutton
  • 53
  • 1
  • 8

2 Answers2

2

You are using conditional rendering wrong way. Put the component in the render and add condition there based on some variable.

onSearchSubmit = () => {
  if (this.state.selectedCategory === this.props.category) {
    console.log('it works')
    this.setState({
      renderProfileCard: true
    })
  } else { console.log('not working') }
}

render() {
  return (
    <div>
      <button onClick={this.onSearchSubmit}>Search</button>
      {this.state.renderProfileCard && <ProfileCard />}
    </div>
  )
}  

Add renderProfile flag to your state.

this.state = {
  renderProfileCard: false
}
Murli Prajapati
  • 8,833
  • 5
  • 38
  • 55
0

You should return the component inside the render hook itself:

render() {
 return (
   <div>
     <button onClick={this.onSearchSubmit}>Search</button>
     {
       this.state.selectedCategory === this.props.category &&
       <ProfileCard /> || null
     }
   </div>
  )
}

If you want to render from outside, the I would suggest you to look at my another post most efficient way of rendering JSX element.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231