onClick not working in React

I don’t understand why when I click on the <ControlsButton /> which has the “onClick” event, the function countSecond doesn’t run. Is there something that I’m missing?

import React, { useState } from 'react';
import './App.css';
import Controls from '../components/Controls'
import Session from '../components/Session'
import ControlsButton from '../components/ControlsButton'

export default function App() {
  const [seshTimer, setSeshTimer] = useState(25);

  function countSecond() {
    setSeshTimer(seshTimer - 1);
    console.log('it worked')
  };

  return (
    <div>
      <div className='dials-wrapper'>
        <Controls title='Break Length'/>
        <Controls title='Session Length'/>
      </div>
      <Session displayedTime={seshTimer} />
      <div className='buttons-wrapper'>
        <ControlsButton icon='pause'/>
        <ControlsButton 
          icon='play'
          onClick={countSecond}
        />
        <ControlsButton icon='reset'/>
      </div>
    </div>
  )
}

I just tried creating a test <button></button> element with onClick={countSecond} in it, and that worked fine. So there must be something wrong with my <ControlsButton /> component?

import React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faPause, faPlay, faArrowsRotate } from '@fortawesome/free-solid-svg-icons'

export default function ControlsButton(props) {
    let iconOne = props.icon === 'play' ? <FontAwesomeIcon icon={faPlay} size='2xl' style={{color: "#ffa257",}} />
        : props.icon === 'pause' ? <FontAwesomeIcon icon={faPause} size='lg' style={{color: "#ffa257",}} />
        : props.icon === 'reset' ? <FontAwesomeIcon icon={faArrowsRotate} size='lg' style={{color: "#ffa257",}} />
        : '';

    return (
        <div className={props.icon === 'play' ? 'controlsButton play' : 'controlsButton singleButtons'}>
            <h1>{props.label}</h1>
            {iconOne}
        </div>
    )
}

I can see that ControlsButton component need “label” too that could be the issue…

Pass label as prop to ControlsButton component.

I’ve solved the problem just now. Turns out the way i did it was incorrect. For it to work I needed to put the onClick={props.onClick} inside the <ControlsButton /> component and this seems to solve the issue

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.