Components Interact (Props)

Penny Pang
path2code
Published in
2 min readDec 18, 2018

Render( ) method can also return another kind of JSX component instances.

“Crazy” component renders “OMG” component

Import

If you have two separate .js files, the file is invisible to each other. To get two files to communicate you have to import . This is called named exports. You always need to wrap your imported names in { }

import { ComponentClass } from '/file.js' ;

Export

you also need to put export in front of the ClassName from another file you’re import to. You can export var , let , funtion , class or const .

this.props

Information gets passed from one component to another. Every component has something called props which is an object that holds information.

To reveal component’s props:

console.log(this.props);

You can pass information to a React component through an attribute

Passing a string:

<Example message="This is some top secret info." />

Passing an array (need {}):

<Greeting myInfo={["top", "secret", "lol"]} />
Notice the ReactDOM.render( ) section in passing the string

Render a Component’s props

Making a component (from component class) to display passed-in information

  1. Find the component class that is going to receive that information
  2. Include this.prop.name in the component class’s render ( ) method in return statement

Passing information to a component from a different component

export a component from a .js file and then import to another file

We are passing “Greeting” Component Instance in the render( ) method

if there’s two prop then add into Component Instance like this:

<Greeting name="Alison" signedIn={false}/>

Passing Event Handler in Component Class

Event Handler in a Component comes in function (similar to render method)

note the { } in return statement as handleEvent is a JavaScript

Pass an Event Handler as a prop

If you want to pass it as a prop, you have to give a Component Instance a name with value. It doesn’t matter what name you want to use. The following code passes a function from <Talker /> to <Button /> where <Talker /> contains a function talk()

Your prop value should be the information that you want to pass

<Button hello = "this.talk" />

this.props.children

Every component’s props object has a property named children.

Component Instance <MyComponentClass /> have been self-closing tag which is the same as <MyComponentClass> ... </MyComponentClass> the this.props.children returns everything in between MyComponentClass

If a component has more than one child between its JSX tags, will return those children in an array.

defaultProps

Simply set your Component Class to .defaultProps

--

--

Penny Pang
path2code

Full-time UX/UI Designer, Part-time online entrepreneur, Casual food blogger and innovation advocate