Search code examples
reactjsrenderstateless

How to render a stateless functional component from another component


I'm new on React. I wrote a project on which there is a search component. the search works fine ( I checked on console.log) but I don't know how to call the stateless function component on which the search results should be shown?

class SearchCard extends Component {
  // qQuery is a variable for query input
  state = { qQuery: "" };
  
  HandleSearch= async (e) => {
    e.preventDefault();
    const {data:cards}  = await cardService.getAllCards();
    var searchResults = cards.filter((item) =>
      item.qTopic.includes(this.state.qQuery) || 
      item.qArticle.includes(this.state.qQuery)
    );
    this.setState({ cards : searchResults }); 
    //   console.log('search results ',searchResults, '  cards ',this.state);
    return <CardRender cards={cards}/> 
  }  

  render() {
    return (
      <React.Fragment>
        <form className="form" onSubmit={ this.HandleSearch }>
          <div className="input-group md-form form-sm form-1 pl-4 col-12">

const CardRender = ({cards,favs,onHandleFavs}) => {
  return (         
    <div className="row">
      {cards.length > 0 &&
        cards.map((card) =>
          <Card key={card._id}
            card={card} 
            favs={favs} 
            onHandleFavs={() => onHandleFavs(card._id)}
          />
      }
    </div>
 );
}
     
export default CardRender;

screenshot


Solution

  • You should add the <CardRender cards={cards}/> to the element render returns (at the place you want it to be) and render it if state.cards is not empty.

    Something like this

    class SearchCard extends Component {
      // qQuery is a variable for query input
      state = { qQuery: "" };
      
      HandleSearch= async (e) => {
        // ...
        this.setState({ cards : searchResults }); 
      }
    
      render() {
        return (
          <div>
            ...
            {cards?.length && <CardRender cards={cards}/>}
          </div>
        );
      }
    }