Zaid
Zaid

Reputation: 29

Not able to change the value of an element using react

I am new to React and I am trying to change the value of an element every time i click on the button. I look online and I think it should be working but for some reason it's not! thanks in advance

import React from 'react';
import ReactDOM from 'react-dom';

const App = () => {
  let showDetails = false;
  const visabillty = () => {
    showDetails = !showDetails;
  };

  return (
    <div style={{textAlign: 'center', margin: '40px'}}>
      <h1>Visailty Project</h1>
      <button onClick={visabillty}>
        {showDetails ? 'show Details' : 'hide Deatils '}
      </button>
      <h1> {showDetails ? 'hello' : 'buy'}</h1>
    </div>
  );
};

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

Upvotes: 2

Views: 60

Answers (1)

Ismael Padilla
Ismael Padilla

Reputation: 5566

In order to make persistent changes to React components, you should make use of the useState hook. See: state and lifecycle.

Try the following:

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

const App = () => {
  const [showDetails, setShowDetails] = useState(false);
  const visabillty = () => {
    setShowDetails(!showDetails);
  };

  return (
    <div style={{textAlign: 'center', margin: '40px'}}>
      <h1>Visailty Project</h1>
      <button onClick={visabillty}>
        {showDetails ? 'show Details' : 'hide Deatils '}
      </button>
      <h1> {showDetails ? 'hello' : 'buy'}</h1>
    </div>
  );
};

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

Upvotes: 6

Related Questions