Is there a way to activate the onClick event in Reactjs within the render method rather than the

Is it possible to assign an onClick function when performing a conditional render outside of the React return statement?

I tried adding code on Stackoverflow but couldn't get any syntax help or eslint after spending an hour in their editor. :D

section:hover {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"/>

<script type="text/babel">

const RotateOnClick = ( {rotated, handleChange} ) => {
  if (rotated) {
    return <section onClick={handleChange}>I'M ROTATED! Click me to rotate again!</section>
  } else {
    return <section onClick={handleChange}>I'm not rotated. Click me to rotate!</section>  
  }
}

class Rotator extends React.Component {

  // Change state to true to see that it renders if toggled
  state = {
    isRotated: false
  }
  
  toggleRotation = () => {
    // Outdated initial code when asking the question
    // console.log("React doesn't like me. It will never call me :( ")
    
    console.log("Yei, it works! React likes me again")
    const { isRotated } = this.state
    this.setState( {isRotated: !isRotated })
  }
    
  render() {
    const { isRotated } = this.state
    
    let conditionalRender;    
    if (isRotated) {
      conditionalRender = <RotateOnClick rotated handleChange={this.toggleRotation} />
    } else {
      conditionalRender = <RotateOnClick handleChange={this.toggleRotation} />
    }
  
    return (
    <div className="hover">
      {conditionalRender}
    </div>
    );
  }
}

ReactDOM.render(
    <Rotator />,
    document.getElementById('root')
);
</script>

Answer №1

<RotateOnClick rotated onClick={this.toggleRotation} />

simply adding an event handler to a component does not guarantee it will respond to click events. It's important to remember that components cannot have event handlers assigned directly to them!

Instead, you must pass the event handler to the component, like so:

<RotateOnClick rotated clickHandler={this.toggleRotation} />

and then use this prop within the render method:

const RotateOnClick = ( {rotated, clickHandler} ) => {
  if (rotated) {
    return <section onClick={clickHandler}>I'M ROTATED! Click me to rotate again!</section>
  } else {
    return <section onClick={clickHandler}>I'm not rotated. Click me to rotate!</section>  
  }
}

By following this pattern, your React components should function as expected once more ;)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing the issue with using transition(myComponent) in this React 18 application?

Recently, I have been immersed in developing a Single Page Application using the latest version of React 18 and integrating it with The Movie Database (TMDB) API. My current focus is on enhancing user experience by incorporating smooth transitions between ...

What is the best way to center the startIcon material ui icon?

I'm having trouble keeping the icon button centered on my page. When I add left: "0.5rem" to the sx prop, it ends up pushing the button icon even further away from center. I'd prefer not to use makeStyles to manually override the position. Any ad ...

Is there a way to change the color of a Material-UI snackbar without creating a new one for each color?

Is there a way to change the color of a snackbar in material-ui without creating a new one for each color? It seems that the example sandbox only has one color, while the others are static. ...

Renaming and destructuring of an array's length using ReactJS

I am working with a reduce function shown below: let el = scopes.reduce ((tot, {actions}) => tot + actions.length, 0); I attempted to modify it as follows, but it appears that this is not the correct approach: let el = scopes.reduce ((tot, {actions.l ...

Refreshing GIF images in React using forceReload

In order to restart the gif animation every 12 seconds or whenever the activeIndex changes, I need to reload a GIF image with CHECKMARK_ANIMATION_ICON as the source. Below is the code: const reloadImgSource = (imgSource) => { setTimeout(() =& ...

The external typing file encounters an issue when trying to locate the relative path to its own index.d.ts file

While working on my project and using react-color as a dependency, I encountered an issue with the tsc import failing. The error message displayed: node_modules/@types/react-color/lib/components/sketch/Sketch.d.ts(2,41): error TS2307: Cannot find module & ...

Oh no! A critical mistake has occurred: Mark-compact operations are not working efficiently near the heap limit, leading to a failed allocation due to the

My project is not particularly complex, I only just started it. However, when I run the command npm run dev, node js consumes more than 4GB of memory and eventually crashes with a fatal error: --- Last few GCs --- [16804:0000018EB02350F0] 128835 ms: Mar ...

Error message: There appears to be a type error within the labelFunc of the KeyBoardDatePicker component in the Material-UI

I am currently working with a material-ui pickers component: <KeyboardDatePicker value={selectedDate} onChange={(_, newValue) => handleClick(newValue)} labelFunc={renderLabel} disableToolbar variant='inline' inputVariant=& ...

I'm attempting to render HTML emails in ReactJS

I have been attempting to display an HTML page in React JS, but I am not achieving the same appearance. Here is the code snippet I used in React JS: <div dangerouslySetInnerHTML={{ __html: data }}/> When executed in regular HTML, the page looks lik ...

The power of Webpack in handling .css files

mm2:OptionsAPI ivan$ npm -v 6.13.4 When I try to include a .css file, import BaseTable, { Column } from 'react-base-table' import 'react-base-table/styles.css' An error occurs with the following message: ERROR in ./node_modules/rea ...

Activate the Material UI Datepicker by pressing the tab key

Is there a way to open the Datepicker by pressing the tab key instead of clicking in the textbox? It would be more convenient when entering multiple fields. I am not sure how to achieve this functionality: <MobileDatePicker variant="outlined" label ...

Chip-styled material-ui select dropdown option

Is it achievable to design a dropdown selection using material-ui that resembles a Chip component similar to this example? If yes, can you guide me on how to begin? ...

Using Material UI and React to beautifully style selected components

In React with material UI, I have a datatable that displays data. Here's an example of the output: <button class="MuiButtonBase-root MuiTab-root MuiTab-textColorPrimary Mui-selected MuiTab-fullWidth" tabindex="0" type="button" role="tab" aria-sele ...

Setting the transition time for adding or removing components in ReactJS CSS

As the list component changes in size based on its children, it tends to move around abruptly. Applying transition: 'all 0.3s ease' doesn't resolve this issue since it's the layout that is affected by the number of children rather than ...

What is the best way to pass props in React?

Develop the App2.js component and integrate it into App.js. Utilize s3 as props z1 within App2. Transfer it to a page in App2 as props. How should I handle passing props z1? static getDerivedStateFromProps(props, state) { return { z1: props.s3 } } ...

Converting Background Images from html styling to Next.js

<div className="readyContent" style="background-image: url(assets/images/banner/banner-new.png);"> <div className="row w-100 align-items-center"> <div className="col-md-7 dFlex-center"> ...

Can an input element be used to showcase a chosen image on the screen?

I would like to display the selected image from an input element. Can this be done with a local file, accessing the image on the client side, or do I need to upload it to a server? Here is my React code attempt: I can retrieve the correct file name from t ...

What could be causing my Dialog checkbox to malfunction?

I've encountered an issue with my component for the Dialog and Checkbox. When the checkbox is outside of the Dialog, everything works fine. However, when it's inside the Dialog, the update doesn't seem to work as expected. I'm not sure ...

What are the reasons behind the inability to import an image file in Next.js?

Having an issue with importing image file in Next.js I'm not sure why I can't import the image file... The image file is located at 'image/images.jpg' In Chrome browser, there are no error messages related to the image, However, in ...

Verification of input fields in Ant Design Form

Recently I started using AntD and I need to set up a validation rule for an input field that accepts either a phone number or email address. However, the code snippet I tried doesn't seem to work as expected: <Form.Item ...