Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  • 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
like image 621
Clarice Bouwer Avatar asked Oct 06 '19 03:10

Clarice Bouwer


People also ask

Can I add onClick to a component React?

The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app. Event names are written in camelCase, so the onclick event is written as onClick in a React app. In addition, React event handlers appear inside curly braces.

How do you use onClick function in React?

React events are written in camelCase syntax: onClick instead of onclick . React event handlers are written inside curly braces: onClick={shoot} instead of onClick="shoot()" .

Does onClick work on Div React?

To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.


1 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>
  )
}
like image 77
Agney Avatar answered Sep 21 '22 07:09

Agney