angry_kiwi angry_kiwi - 1 month ago 11
Javascript Question

react - how to show relevant element when click button

I have component that renders jsx like this

<section>
<button id={item.uniqueID}>show input</button>
<div>
<input type="text" class="hide" />
</div>
<button id={item.uniqueID}>show input</button>
<div>
<input type="text" class="hide" />
</div>
<button id={item.uniqueID}>show input</button>
<div>
<input type="text" class="hide" />
</div>
</section>


I want this behavior, when I click the button in the first div, the input in the first div will show. Similarly, I click the button in the third div the input in third div will show.

How you do that in react?

Answer

If it were me I would make a new component out of: show input

Lets call it <InputToggler/>

and then it would have a state of inputHidden for its own input and use classes to determine if it should show or not and the button would have an onclick handler to toggle the state of hidden or shown. Here is a pen showing exactly that

http://codepen.io/finalfreq/pen/VKPXoN

class InputToggler extends React.Component {
  constructor() {
    super();

    this.state = {
      inputHidden: true
    }
  }

  toggleInput = () => {
    this.setState({
      inputHidden: !this.state.inputHidden
    })
  };

  render() {
    const inputClass = this.state.inputHidden ? 'hide' : '';
    const buttonLabel = this.state.inputHidden ? 'show input' : 'hide input'
    return (
      <span>
        <input type="text" className={inputClass} />
        <button onClick={this.toggleInput} id={this.props.item.uniqueID}>          
          {buttonLabel}
        </button>
      </span>
     )
  }
}