Clarice Bouwer
Clarice Bouwer

Reputation: 3811

onClick not working on my React component

I have composite components. The parent component should be able to pass props to child components when clicked.

When I add the onClick handler to the search component of my header, there are no messages printed to the console.

Parent component header

import React from "react"
import styled from "styled-components"
import Search from "./search"

const Container = styled.header``
const Wrapper = styled.div``

function Header () {
  function toggleSearch(e) {
    e.preventDefault();
    console.log('Search')
  }

  return ( 
    <Container>
      <Wrapper>
        <Search onClick={toggleSearch} />
      </Wrapper>
    </Container>
  )
}

export default Header

and the child component search

import React from 'react'
import styled from 'styled-components'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faSearch } from '@fortawesome/free-solid-svg-icons'

const Container = styled.span``
const Icon = styled(FontAwesomeIcon)

const Search = () => {
  return (
    <Container>
      <Icon icon={faSearch} />
    </Container>
  )
}

export default Search

How do I get my click event to fire?


I am using

"react": "^16.9.0"
"styled-components": "^4.3.2

Upvotes: 5

Views: 4770

Answers (3)

Dacre Denny
Dacre Denny

Reputation: 30360

This is because the custom Search component does not implement an onClick callback prop. Extending Search with the following should resolve the issue:

/* Add props argument */
const Search = (props) => {
  return (
    {/* Add onClick prop to span, and pass through supplied onClick prop */}
    <Container onClick={props.onClick}>
      <Icon icon={faSearch} />
    </Container>
  )
}

Upvotes: 3

Agney
Agney

Reputation: 19204

Since Search is a component, the onClick event handler has to be passed onto the element inside it. onClick is as any other prop on a component and has no default meaning.

const Search = ({onClick}) => {
  return (
    <Container onClick={onClick}>
      <Icon icon={faSearch} />
    </Container>
  )
}

Upvotes: 6

Shashank
Shashank

Reputation: 324

you should add that onClick props in Search component. You are not utilising that props. If you want on click on let say on icon element then you should do something like this.


const Search = (props) => {
  return (
    <Container>
      <Icon icon={faSearch} onClick={props.onClick} />
    </Container>
  )
}


If you want it to add on Container element then you should do like this.


const Search = (props) => {
  return (
    <Container onClick={props.onClick}>
      <Icon icon={faSearch} />
    </Container>
  )
}


Upvotes: 2

Related Questions