R
R
Rapen2017-04-10 19:07:38
React
Rapen, 2017-04-10 19:07:38

How to access child jsx element?

This is the half-finished code from the todo list. There is a functional jsxElems component that generates div elements, how to access the input element in each div element?

const arr = [
    {
        id:'1',
        value:"Learn React"
    },
    {
        id:'2',
        value: 'Learn Redux'
    }
];
function jsxElems(arr){ 
        return ( 
                    <div>
             {arr.map((n,i) => {
              return (<div className="listElem" key={i}>{n.value}
              <input type="checkbox"/>
              </div>);
            })}
        </div>);
  } 
class App extends React.Component { 
 	constructor(props){
    super(props);
    this.state = { 
      jsxElems: jsxElems(arr)
      }
    }			
  handleAdd =(e) =>{
    let _valOfInput = document.querySelector(".val").value;
        if(!_valOfInput){
            return;
        }
      arr.push({
        value: _valOfInput 
      });
    this.setState({
           jsxElems:jsxElems(arr)
        })
  }
  handleRemove = (e) =>{
    let list = jsxElems(arr);
        for(let i = 0;list.length;i++){
            list[i]
        }
  }
  render() { 
    return (	
      <div className="todoMain">	
      <span className="todo">TODO</span>
      <input className='val' placeholder="Add a Task..." type="text"/>
      <input  type="button" value='Add' onClick={this.handleAdd}/>
      <input type="button" value='Clear' onClick={this.handleRemove}/>
      {this.state.jsxElems}
      </div> 
      );	
  }
}
ReactDOM.render(<App />,document.getElementById('root'))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad Feninets, 2017-04-11
@Rapen

through refs

contructor() {
   super()

   this.refsList = []
 }

 // ....

 {arr.map((n,i) => {
  return (<div className="listElem" key={i}>{n.value}
  <input type="checkbox" ref={ref => this.refsList.push({ value: n.value, ref })}/>
  </div>);
})}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question