Reputation: 73
I am fairly new to React so any help would be appreciated!
What I am trying to do is create an edit button for my code that allows the user to edit the persons birth year, and their home world. I want the text to appear as a text box when the edit button is pressed, so that the user can change it, and then save it somehow. Here is my code:
class Card extends Component {
render() {
const {imgSrc, cardName, birthYear, onEdit} = this.props;
return (
<div className='card'>
<div className='card-content'>
<div className='card-name'>{cardName}</div>
<img src={`http://localhost:3008/${imgSrc}`} alt='profile'/>
<p>
<span>Birthday:</span>
<span className='birth-year'>{birthYear}</span>
</p>
<p>
<span>Homeworld:</span>
<span className='home-world'>Earth</span>
</p>
<div align='center'>
<button>Edit</button>
</div>
</div>
</div>
Upvotes: 2
Views: 15985
Reputation: 3774
You can have an internal editing
state, based on which the component renders either the input field with the default value as the current value for that field or the <span>
. It flips to true when you press the edit button. You'll also have to conditionally render an update/save button and update the values when save is clicked. This is the general idea.
class Card extends Component {
constructor(props) {
super(props);
this.state = {
editing: false
};
this.newbirthYear = "";
this.newHomeWorld = "";
}
render() {
const { imgSrc, cardName, birthYear, homeWorld, onEdit } = this.props;
return (
<div className="card">
<div className="card-content">
<div className="card-name">{cardName}</div>
<img src={`http://localhost:3008/${imgSrc}`} alt="profile" />
<p>
<span>Birthday:</span>
{this.state.editing ? (
<span className="birth-year">{birthYear}</span>
) : (
<input
type="text"
defaultValue={birthYear}
ref={node => {
this.newbirthYear = node;
}}
/>
)}
</p>
<p>
<span>Homeworld:</span>
{this.state.editing ? (
<span className="home-world">{homeWorld}</span>
) : (
<input
type="text"
defaultValue={homeWorld}
ref={node => {
this.newHomeWorld = node;
}}
/>
)}
</p>
<div align="center">
<button
onClick={() => {
this.setState({ editing: true });
}}
>
Edit
</button>
</div>
</div>
</div>
);
}
}
Hope this helps !
Upvotes: 3
Reputation: 1079
You are going to have to setState based on the incoming props. Then in your form you would need to do something like
<input type='text' defaultValue={this.state.user.birthday} />
Upvotes: 0