unpangloss
unpangloss

Reputation: 409

React JSX: How to access parent attributes in this manner?

<Wrapper className="form-group" inputAttrs={{id: 'fullname', className: 'form-control'}}>
  <label htmlFor={this.parent.props.inputAttrs.id} >Full Name</El>
  <input {...this.parent.props.inputAttrs} />
</Wrapper>

Is this possible or what is the better approach to this?

Upvotes: 1

Views: 10178

Answers (2)

Corey Trombley
Corey Trombley

Reputation: 136

Based on what you have displayed. The parent component would not be the Wrapper component. It would be whatever component is requiring that file.

var MyComponent = React.createClass({
  render: function() {
    return (
      <!-- anything passed as a prop to OtherComponent is passed down --> 
      <OtherComponent propOne={this.state.propOne} propTwo={this.props.propTwo}/>
    );
  }
});

var OtherComponent = React.createClass({

 propTypes: return {
   propOne: React.PropTypes.string,
   propTwo: React.PropTypes.object
 },
 render: function() {
   return (
     <!-- Wrapper is the child of OtherComponent -->
     <Wrapper {...this.props} >
       <!-- input is the child of OtherComponent -->
       <input />
     </wrapper>
   );
 }
});

Now Wrapper would have a this.props.children that it could do things with, but I am not sure what you would do with it at this point. Now I could be reading this all wrong and you are displaying the rendered html/react. If that is the case please let me know and I will revise my answer.

Upvotes: 0

Jeremy D
Jeremy D

Reputation: 4855

This is what props are for. You use props to pass data from a Parent component to its children. If you need to modify the parent properties from one of the children, you should have a state on the parent, and pass a callback to a child, and it could just call setState in the callback.

Everything is stated in the documentation.

Upvotes: 4

Related Questions