Reputation: 1532
This is a more general question. I need an idea to handle a problem, so I won't give you specific code.
I have a list of items, that are output through a map function. Basically all is good. But I want to embed a component, that would show an input to rename that item.
The idea is that someone clicks on some button, that triggers rename handler, and there is an input there to rename that item.
So, the renaming component works, the only thing that I stuck with is this:
in very general terms the code is this
list.map(item => <li key={item.id}>{item.name} <Rename inputValue={this.state.value} inputHandler={this.inputHandler} /></li>)
How to make this rename show up only when then the trigger is clicked only for that item that was clicked to be renamed ? The thing also is, that this input would be bound to a state, and there would be a handler to change that state. And that means, that every input would have the same state and same handler.
So, I hope I was able to describe a problem, how generally things like these would be solved in react?
Upvotes: 0
Views: 1284
Reputation: 3473
That is pretty easy to realize in react.
You just need to keep the state in the component.
I show you a very simple mockup:
class Item extends React.Component {
constructor(props) {
super(props);
this.state ={
showInput: false,
value: props.value
}
}
triggerClick() {
this.setState({showInput: true});
}
handleChange(value) {
// do update value
}
render() {
const {value, showInput} = this.state;
return (
<div>
<button onClick={this.triggerClick}>show input</button>
{showInput ?
<input type="text" value={value} onChange={this.handleChange}/>
: null}
<p>{value}</p>
</div>
);
}
}
And then use what you mention map method
to build it.
list.map(item => <Item value={item.value}/>)
It would work as you need.
Upvotes: 3