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
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.
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()" .
To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.
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>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With