Adding OnClick on button component

Viewed 130

I have created a button component that I can reuse on other pages

import styled from 'styled-components'

const Button = styled.button`
  background: #0070f3;
  border-radius: 5px;
  position: relative;
  display: inline-block;
  line-height: normal;
  font-family: inherit;
  font-size: inherit;
  color: #FFF;
  font-weight: 500;
  text-decoration: none;
  padding: 10px 20px;
  transition: 0.3s all ease;
  outline: 0;
  border: 0;
  cursor: pointer;
`
export const ButtonComponent = ({ children, className }) => {
  return (
    <Button className={className}>{children}</Button>
  )
}

But I would like to give each Button component a different onClick link. How can I do that exactly?

4 Answers

You can pass onClick event as a prop to your common component and in that onClick prop you can pass different functions/events you would like to execute on the click of that button

import styled from 'styled-components'

const Button = styled.button`
  background: #0070f3;
  border-radius: 5px;
  position: relative;
  display: inline-block;
  line-height: normal;
  font-family: inherit;
  font-size: inherit;
  color: #FFF;
  font-weight: 500;
  text-decoration: none;
  padding: 10px 20px;
  transition: 0.3s all ease;
  outline: 0;
  border: 0;
  cursor: pointer;
`
export const ButtonComponent = ({ children, className, onClick }) => {
  return (
    <Button className={className} onClick={onClick}>{children}</Button>
  )
}

You could just give the button another param, where you give him a reference to a function, like this:

import styled from 'styled-components'

const Button = styled.button`
  background: #0070f3;
  border-radius: 5px;
  position: relative;
  display: inline-block;
  line-height: normal;
  font-family: inherit;
  font-size: inherit;
  color: #FFF;
  font-weight: 500;
  text-decoration: none;
  padding: 10px 20px;
  transition: 0.3s all ease;
  outline: 0;
  border: 0;
  cursor: pointer;
`
export const ButtonComponent = ({ children, className, myFunction }) => {
  return (
    <Button className={className} onClick={myFunction}>{children}</Button>
  )
}

Just take onClick function as a props in your button

export const ButtonComponent = ({ children, className, onClick }) => {
  return (
    <Button className={className} onClick={onClick}>{children}</Button>
  )
}

You can also just pass the props like this to the child component. That way, you can pass other events to the components directly (https://reactjs.org/docs/events.html) or override some other props for a specific use case etc.

export const ButtonComponent = ({ children, className, ...props }) => {
  return (
    <Button {...props} className={className}>{children}</Button>
  )
}

In the parent you'd call it like.

<ButtonComponent onClick={() => alert('Hello')}>Click me</ButtonComponent>
Related