onClick not working on my React component

Viewed 3260

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
  • When I add a button to the Header, the click event fires.
  • When I change the Search container to a button instead of a span then the button can be clicked but the message is not written to the console.

How do I get my click event to fire?


I am using

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

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>
  )
}

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>
  )
}


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>
  )
}
Related