0

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.

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.