Autoplay

    Use React Components as Children for Other Components

    Joe MaddaloneJoe Maddalone

    The owner-ownee relationship is used to designate a parent-child relationship with React components as it differs from the DOM relationship. This lesson demonstrates how composable React can be when using stateless functions to display data.

    reactReact
    0.14 - 16
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 Important feature of React is the fact a React component can output or render other React components. We've got a very simple component here. It has a state with a value of text. It's got an update method which is going to update that value of text from an event.

    00:15 In our JSX, we're outputting our state.text value. We're also outputting an input and its on-change event is tied to our update event. I'm going to save that. We're going to try it out in the browser. Anything I type here is going to update the state.text.

    00:32 What we're going to do is we're going to create a new component. This is going to be a stateless function component. We're going to call it widget. It's going to take in props. We're going to return this input JSX right here. We're just going to drop that down there, get this guy into one line.

    00:50 Here where we had our input, we're going to go ahead and render a widget component. We can self-close that. We're just going to have an update prop and into that we're going to pass this.update.bind to this.

    01:04 Now, down here, where we had this.update.bind(this), we're going to go ahead and just say props.update, since it's passed in as a prop and we don't need the binding. We'll save that. Here in the browser when we type, our child component is updating the state of our parent component.

    01:23 This also means that we could have a few of these guys on the page and every time we type in one of them, it'll update the value in our parent component.

    Discuss

    Discuss