Getting Components to interact
Render methods can also return another kind of JSX - component instances
Exporting Components
export const nameOfItem = {};
You can make multiple exports within the same file
In a different file, import the name of the variable from the first file.
e.g. In NavBar.js: export class NavBar extends React.Component . . .
In ProfilePage.js: import {NavBar} from './NavBar.js';
this.props - Store dynamic information in React
A component can pass information to another component.
Every component has something called props.
props is an object that holds information about component.
To see a component's props object, use expression this.props
Give component an attribute to pass info to.
To pass information to a component, you need a name for the information that you want to pass.
If you want to pass info that isn't a string, wrap info in curly braces {}
How you would pass an array:
<Greeting myInfo = { [ "top", "secret", "12"] } />
<Greeting name="Henry" city="London" age={2} />
Passing information to a component's props object:
ReactDOM.render(
How to make a component display passed-in info
- Find the component class that is going to recieve that info
- Include this.props.name-of-info in that components class's render method's return statement
Pass props from component to component
You can use props to make decisions.
You can check if a particular value has been given to a prop before returning another prop.
You often pass functions as props.
It is common to pass event handler functions.
You have to define an event handler before you can pass one anywhere
You define an event handler as a method on the component class, just like the render method.
Recieve an event handler as a prop
Naming Convention
First name you choose -> Event handler
Second name you choose -> name of prop you pass to
What type of event handler are you listening for?
e.g. click, you name event handler handleClick
Your prop name should be the word on plus your event type. e.g. onClick
this.props.children
Every component's props object hs a property named children
this.props.children will return everything in between a component's opening and closing JSX tags.
Components don't have to be self closing!
If a component has more than one child between JSX tags, this.props.children will return children in an array.
If a component has only one child this.props.children will return single child, not wrapped in an array.
if(this.props.children instanceof Array){
titleText += 's' ;
}<-- checks if this.props.children returns an array(multiple items), then adds an 's' to the title to make it plural.
defaultProps
<button>
{this.props.text}
</button>
If nobody passes any text to button, then it will display blank.
It would be better if button could display default message instead.
</div>