DEV Community

Nikhil Chandra Roy
Nikhil Chandra Roy

Posted on

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

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) {
    super(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}
    </div>

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

export default App

Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
fernandoperigolo profile image
Fernando Souza

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

Collapse
 
nikhilroy2 profile image
Nikhil Chandra Roy

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.

Collapse
 
fernandoperigolo profile image
Fernando Souza

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

Collapse
 
nikhilroy2 profile image
Nikhil Chandra Roy

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.