Theo
Theo

Reputation: 3149

Using click events on button click

I am new to React and let's suppose we have the following piece of code.

const showDetails = () => {
    console.log('Show details')


}
const template = (
    <div>
        <h1>Vibility Toggle</h1>
        <button onClick={showDetails}>Show details</button>
    </div>
)

var app = document.getElementById('app')

ReactDOM.render(template, app)

What I want is to change the button's title from Show Details to Hide Details when it is clicked. So I' ve thinking to get the click event inside the function and change the title by using a ternary operator. How to do that?

Thanks Theo.

Upvotes: 2

Views: 69

Answers (3)

Lu&#237;s Ramalho
Lu&#237;s Ramalho

Reputation: 10218

You can also keep it simple by doing something like:

let show = true;

const showDetails = event => {
  show = !show;
  event.target.innerHTML = show ? "Show Details" : "Hide Details";
};

const template = (
  <div>
    <h1>Vibility Toggle</h1>
    <button onClick={showDetails}>Show Details</button>
  </div>
);

var app = document.getElementById("app");

ReactDOM.render(template, app);
<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="app"></div>

Upvotes: 1

Nikas
Nikas

Reputation: 247

you need to use state in React.please read this documentation for state in React React State. here is the sample code to change title using ternary operator in React

import React, { Component } from 'react';
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            showDetails: true
        }
    }

    showDetails = () => {
        console.log('Show details')
        this.setState({ showDetails: !this.state.showDetails })
    }

    render() {
        return (
            <div>
                <h1>Vibility Toggle</h1>
                <button onClick={() => this.showDetails()}>{this.state.showDetails ? 'Show Details' : 'Hide Details'}</button>
            </div>
        )
    }
}
export default App

Upvotes: 1

ankitkanojia
ankitkanojia

Reputation: 3122

you can use the state to handle toggle event in react. I have added a snippet of toggle handler.

import React, { Component } from 'react';

class App extends Component {

    state = {
        isVisible : true
    }

    toggleDetails = () => {
        this.setState({
            isVisible : !this.state.isVisible
        });
    }

    render() {
        return (<div>
            <h1>Vibility Toggle ({this.state.isVisible ? "is Visible" : "is Not Visisble"})</h1>
            <button onClick={this.toggleDetails}>{!this.state.isVisible ? "Show details" : "Hide details"}</button>
        </div>)
    }
}

export default App;

Upvotes: 3

Related Questions