Don Hosek
Don Hosek

Reputation: 1021

Click button, replace enclosing component with different component

New to React so this is probably a stupid question:

I've got a component that I want to replace with an alternate component (I think), so that if I click on a button that exists for editing the details, it will replace the display stuff with editing. The idea being that I start out rendering

<div>
  <h1>{this.props.journal.name}</h1>
  <button>Edit details</button>
</div>

and I click on the button and it turns into

<div>
  <form>
    <input type="text" value={this.props.journal.name} />
    <button>Save</button>
    <button>Cancel</button>
  </form>
</div>

How would I manage this? I'm guessing that I should be doing something with state as well.

Upvotes: 0

Views: 301

Answers (2)

BugsArePeopleToo
BugsArePeopleToo

Reputation: 2996

The useState hook makes it easy to set up a piece of state - showEdit in this case, the function to change it toggleShowEdit, and set a default - the "true" passed into the useState hook.

Then in your output just show whatever you want based on the state you are changing. Here, a simple expression based on the boolean value showEdit works nicely.

More on the useState hook: https://reactjs.org/docs/hooks-state.html

import React, { useState } from 'react';

const MyComponent = (props) => {
  const [showEdit, toggleShowEdit] = useState(false);

  return (
    <>
      {!showEdit &&
        <div>
          <h1>{props.journal.name}</h1>
          <button onClick={() => toggleShowEdit(true)}>Edit details</button>
        </div>
      }
      {showEdit &&
        <div>
          <form>
            <input type="text" value={props.journal.name} />
            <button>Save</button>
            <button onClick={() => toggleShowEdit(false)}>Cancel</button>
          </form>
        </div>
      }
    </>
  );
};

export default MyComponent;

Upvotes: 2

Shmili Breuer
Shmili Breuer

Reputation: 4147

Assuming you have a class based component

First create a state object (before the render function)

state = {edit: false}

Then in your component do this

{!this.state.edit ? (
<div>
    <h1>{this.props.journal.name}</h1>
    <button onClick={() => this.setState({edit:true})}>Edit details</button>
</div>
) : (
<div>
    <form>
        <input type="text" value={this.props.journal.name} />
        <button onClick={() => this.setState({edit:false})}>Save</button>
        <button onClick={() => this.setState({edit:false})}>Cancel</button>
    </form>
</div>
) }

Hope this helps

Upvotes: 1

Related Questions