Communication between components

Reusing functions is one of our goals as developers, and we have seen how React makes it easy to create reusable components. Reusable components can be shared across multiple domains of your application to avoid duplication.

Small components with a clean interface can be composed together to create complex applications that are powerful and maintainable at the same time.

Composing React components is pretty straightforward; you just have to include them in the render method:

  import { object } from 'prop-types';

const Profile = ({ user }) => (
<div>
<Picture profileImageUrl={user.profileImageUrl} />
<UserName name={user.name} screenName={user.screenName} />
</div>
);

Profile.propTypes = {
user: object
};

For example, you can create a Profile component by simply composing a Picture component to display the profile image and a UserName component to display the name and the screen name of the user.

In this way, you can produce new parts of the user interface very quickly, writing only a few lines of code. Whenever you compose components, as in the preceding example, you share data between them using props. Props are the way a parent component can pass its data down the tree to every component that needs it (or part of it).

When a component passes some props to another component, it is called the owner, irrespective of the parent-child relationship between them.

For example, in the preceding snippet, Profile is not the direct parent of Picture (the div tag is), but Profile owns Picture because it passes down the props to it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset