Sritharni CN
Sritharni CN

Reputation: 135

How to enable/disable a button on click of a checkbox in React js?

Can someone help me with this code I've researched quite a lot and I'm stuck.

class App extends Component{
   constructor(props){
     super(props);
    this.isChecked=this.isChecked.bind(this);
   }
 }
 isChecked = (chk,sub1) => {
   var btn = document.getElementById(sub1);
     if (chk.checked == true) {
         btn.disabled = false;
     } else {
         btn.disabled = true;
     };
  
 }



function App(){         
return(
     <form>
    <div className='check'>
      <input 
      type='checkbox'
      className='checkbox'
      id='termschkbx'
      onchange="isChecked(this,'sub1')"
      />
      
      <span>I agree to Terms & Conditions.<a href="" className='readme'>Read here</a> </span>
    </div>
    <div>


    <button
    type="submit"
     id="sub1"
     disabled='disabled'
     className=" createaccount" 
     type="submit">CREATE ACCOUNT</button>
    </div>
    </form>
)
}

How to resolve this?

ERROR : Identifier 'App' has already been declared.

Is there any efficient way to do this?

Upvotes: 1

Views: 3108

Answers (2)

Monty Tomar
Monty Tomar

Reputation: 65

So you can achieve the functionality using the state in the App component.
class App extends Component{
   constructor(props){
     super(props);
    this.state={isHidden : false } // button will not be hidden initally.
   }
 }
 isChecked = () => {
  this.setState((state)=>({isHidden : !state.isHidden})) /* we're setting the state value isHidden equal to the negation of previous value of isHidden onChange event of checkbox */
 }

render(){
return(
     <form>
    <div className='check'>
      <input 
      type='checkbox'
      className='checkbox'
      id='termschkbx'
      onChange={this.isChecked}
      />
      
      <span>I agree to Terms & Conditions.<a href="" className='readme'>Read here</a> </span>
    </div>
    <div>


    {this.state.isHidden && <button
    type="submit"
     id="sub1"
     className=" createaccount" 
     type="submit">CREATE ACCOUNT</button> }
    </div>
    </form>
)
}

Upvotes: 0

Is there any way to style my submit button ? (i.e) It should have one particular color when disabled and one particular color when enabled.

There is a CSS selector :disabled which you can use to style the button when it is disabled.

Look like you haven't used any CSS solution, I would suggest you using CSSModule or styled components

ERROR : Identifier 'App' has already been declared.

You are defining App twice:

class App extends Component { ...
function App(){ ...

Remove one and will resolve the error, but based on the context, you probably should move the content of the function App() into function render() inside your class App

Also, I wouldn't suggest mix-matching React other frameworks

Upvotes: 1

Related Questions