How to use toggle outside of class component render and toggle inside variable reactjs?

nikhilroy2 profile image nikhilroy2 ・1 min read

How to use toggle outside of class component render and toggle inside variable?
I want to use toggle inside const variable but I am too confused about how I can override this one.
I set an input text when I enter the text I need the toggle after enter the text input
Below the code:

import React, { Component } from 'react'

class App extends Component {
  constructor(props) {

    this.state = {
         mytoggle : false,
         p: ''

  myKey = (e)=> {
    let p = <div>

      <button onClick={()=> this.setState({mytoggle: !this.state.mytoggle})}> Click Me </button>
      {this.state.mytoggle ? <p>
    Lorem ipsum dolor sit amet.
  </p> : null}

    if(e.key === "Enter") {
      this.setState(prev=> ({
        p: [...prev.p, p]
  render() {
    return (
        <input onKeyPress={this.myKey} type="text"/>

export default App

Posted on by:

nikhilroy2 profile



Front-End Web Developer with JavaScript, ReactJs.


markdown guide

I tried to understand your question, but I can't. I recommend you to ask what you want to do as project, the goal, instead ask how to put some code that way.
I see you trying to make react works as you wish instead try to understand how react works.

Can you try to put you question other way? Maybe I can help you


I want to use toggle inside myKey function see codesandbox.io/s/silent-bird-86li3

when I hit enter after type some text I need the click button toggle but the toggle not working, I will appreciate you if you try to fix it.


I made a working POC based in your code and leave some comments in code, codesandbox.io/s/xenodochial-breez...

I hope it helps you


I think, you do not understand properly. now think, I want to make a chat and then send the message then I want to set the delete option or any other button, toggle but without any sending SMS I don't want to toggle. only specific SMS toggle should work so that I can add delete, toggle, edit, copy etc button.