Skip to content Skip to sidebar Skip to footer

Capture Event Of Children In Parent Component React With No Markup Of Own

var React = require('react'); var {Col} = require('react-bootstrap/lib'); var Segment = require('../util/segment-data'); module.exports = React.createClass({ displayName: 'My

Solution 1:

The reason I am avoiding this is because I don't want to specify any html of my wrapper component.

You can use the render callback pattern for this. You specify an event callback for the child. Here is an example of this pattern.

constChild = ({onClick, children}) => (
  <divclassName="child"><buttononClick={onClick}>Click</button><div>value is: {children}</div></div>
);

classParentextendsReact.Component {
  constructor(props){
    super(props);
    this.state = {};
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(event){
    this.setState({value: newDate().toString()});
  }
  render(){
    returnthis.props.children({onClick: this.handleClick, value: this.state.value});
  }
}

You use the components like this.

<Parent>
  {({onClick, value}) =><ChildonClick={onClick}>{value}</Child>}
</Parent>

Only the child markup will be rendered.

Solution 2:

You can do this my applying onClick prop to all children.

render() {
  return React.Children.map(this.props.children, child => {
    return React.cloneElement(child, {
      onClick: this.captureEventHandler
    });
  });
}

Post a Comment for "Capture Event Of Children In Parent Component React With No Markup Of Own"