React Props
React Props
Remember when we presented features of React, we talked about the one way data flow. So what
does it mean?
The approach mean that the data can only travel from a parent to child (top to bottom) not the other
way. Unlike the library and framework, React make sure, that this feature keep exist in its
architecture, but why?
The reason behind, is that if we keep the one way traveling, it make it easier to trace the data and
it’s changing over the component tree, it sound a little bit confusing but let’s see an illustration to
make it easier to understand.
What's props?
To make the one way data flow possible, react uses props.
Props or properties is the tool that react uses to pass data from parent to child.
Let’s think of it as a parameter in JavaScript function.
We can change the value of this parameter but the sets of instructions to be executed remain the
same.
Take your facebook page as an example , you will find on the right your name next to your picture.
In the reality of coding, facebook developers can't create a navbar customized for every profile.
This is only possible using React props.
The structure of these elements will be fixed and the content (name, image url...) will be received as
a props.
JS example
Here is an another example to understand more what we were talking about.
function Greeting(name) {
return "hello " + name;
}
console.log(Greeting('Jon Snow'))// it will display "hello Jon Snow"
console.log(Greeting('Ramsay Bolton')) // it will display "hello Ramzay Bolton"
console.log(Greeting('I am nobody')) // it will display "hello I am nobody"
The function Greeting receive a name as an argument, but whatever the name contain it will add it
to a ‘hello’ and display it.
React example
Now let’s try the same idea with a react component.
function Greeter(props) {
return <h1>hello {props.name}</h1>;
}
// And invoking the <Greeter/> component…
const App = () => {
return (
<div>
<Greeter name="world" /> {/* 💥 "world" is the prop value*/}
<Greeter name="I am the King" /> {/* 💥 "I am the King" is the prop value*/}
</div>
);
};
export default App;
Let's recap!
React Props are like function arguments in JavaScript and attributes in HTML. To send props into a
component, use the same syntax as HTML attributes:
<Greeter name="world" />
function Greeter(props) {
return <h1>hello {props.name}</h1>;
}
As we can see, the component Greeter receive the name as a props and display it in an h1 tag.
Another thing to notice that the props is an object and whatever we pass as attribute in the
component call in the parent.
Notice : Props are immutable which mean that the child can only read the content of a props. It can
not change it.
What’s a prop?
It’s a special keyword in react
A prop should only be a string False
A props is passed as parameter to the component True
A component can have an unlimited number of props, meaning that we can pass as many props as
we wish. Take a look at this example :
<Welcome name= 'Sara' lastName = 'Smith' Age='27'/>
Using props
It’s time to use our first props after creating it!
First thing to do when using props is to pass it as a parameter to the function of the component.
// we always use the keyword props in the function parameter
const Welcome = props =>{
return (
<h1>
`Hello`
</h1>
)
}
We can use any parameter name but by convention we use the keyword props.
App.js
const App = () => (
<div>
<Welcome name="Sara" />
</div>
);
Welcome.js
const Welcome = props =>{
console.log(`props:`,props)
return (
<h1> welcome </h1>
)
}
Output
As we see in the example above, the even if the props passed as a string it arrived to the child as an
object.
Rules of Props
We‘ve said earlier that props are immutable but what if we try to change its value. Take a look at
the example below :
const Welcome = props =>{
console.log(`props:`,props.name)
props.name ='John'// try to change the value into 'John'
return (
<h1> Welcome {props.name}</h1>
)
}
We’ll have the same result as before, that’s because the props are read only.
Function as a props
We know that the props can hold any JavaScript data types, then what’s about function ?
Of course, we can pass a function as props from parent to child. Actually, this trick is used to pass
data from child to parent. Don’t panic, we know that React is one way data flow, but in real life
application, we are obliged some time to get data from the child to the parent.
To make it possible, we take advantage of the function. Here is an example of what we’re talking
about.
App.js
const App = () => {
const alertMyInput = name => alert(name);
return (
<div>
<Welcome name="Sara" alertMyInput={alertMyInput} />
</div>
);
};
Welcome.js
const Welcome = props => {
console.log(`props:`, props.name);
return (
<button onClick={() => props.alertMyInput(`My name is James Brown `)}>
ClickMe
</button>
);
};
Conclusion
We know it’s a lot of stuff, but what we should remember from this skill :
• Props are arguments passed into React components.
• Props are used to insure the communication between the tree of component,
• Props are immutable their value cannot be changed by the child component,
• Props only passed from parent to child.
After execute this code what should be the result?Sandwich Pizza Salad
const Restaurant = props => {
return <div>{props.food} </div>;
};
<Restaurant food="Sandwich" />;
<Restaurant food="Pizza" />;
<Restaurant food="salad" />;
Which type can’t be a props? Not string not function not array
Children prop
Some reminder about HTML, an HTML element is the combination of an opening tag, a content
and a closing tag.
That approach still valid using react. We can create a component and pass some content between the
opening and closing tag. That’s what we call react children.
const App = () => {
return (
<div>
<Welcome>Sarrah </Welcome>
</div>
);
};
Children prop usage
Amazing thing, doesn’t? The value passed between the two tags can be used by the child
component. Only the syntax has changed.
To access to this value we use props.children. Here is an example to understand more.
const App = () => {
return (
<div>
<Welcome>Arya Stark</Welcome>
</div>
);
};
To use a children prop we use a self closing tag to invoke the componentFalse
Style prop
There are many ways to style React with CSS.
We will take a closer look at inline styling.
Inline Styling:
To style an element with the inline style attribute, the value must be a JavaScript object:
Inline Styling
To style an element with the inline style attribute, the value of style attribute must be a JavaScript
object.
<div style={styleObject} > or <div style={{color: “red”, textAlign: “center”}}>
Note: In JSX, JavaScript expressions are written inside curly braces, and since JavaScript objects
also use curly braces, the styling in the example above is written inside two sets of curly braces
{{}}.
Conclusion
One of the simplest way to add style to the component is the inline styling, so we should keep in
mind that :
• The css rules are written in JavaScript so we should change it into JavaScript standard
(camel case, without spacing or dashes).
• The style is written in an object so don’t forget the double curly brackets.
Default props
As we said in the begging of this super skill, the props is a core idea in react architecture.
but let’s take a moment of thinking, if we somehow used a props in a component, but we forget to
send it’s value from the parent. That will produce problem when executing. So React provides a
technique that will help us much. Which is the Default props
Default props
This code defines a very simple ReactHeader component that renders a <h1> element containing a
heading for the documentation of a specified React version.
// Simple React Component
function ReactHeader(props) {
return <h1>React {props.version} Documentation</h1>;
}
In ReactHeader component we are gonna set version prop to 16 everything seems to be working
properly in the ReactHeader component.
//We gonna render ReactHeader with version=’16’
const App = () => { return <ReactHeader version=’16’ />}
//output on the screen :
//React 16 Documentation
Default props
What happens when the version prop is not passed?
You probably might have guessed right. Here is what happens when the ReactHeader component is
rendered without the version prop:
// Simple React Component
function ReactHeader(props) {
return <h1>React {props.version} Documentation</h1>;
}
Since the version prop is not passed, the reference to props.version in the component is undefined.
The output on the screen will be :
//output on the screen :
React undefined Documentation
Solution:
You could fix this by setting default props for the component :
// Simple React Component
function ReactHeader(props) {
return <h1>React {props.version} Documentation</h1>;
}
The component gonna use the default value for the version prop whenever it is not passed.
The component gonna use the default value for the version prop whenever it is not passed.
The solution of not sending an expected props to a component is Default props
function ReactHeader(props) {
return <h1>React {props.version} Documentation</h1>;
}
ReactHeader.defaultProps = {
version: "16"
};
When we don't send a prop value into the ReactHeader component, what will be the displayed
output?
React 16 Documentation
unction ReactHeader(props) {
return <h1>React {props.version} Documentation</h1>;
}
ReactHeader.defaultProps = {
version: "16"
};
PropTypes
Props are a very important mechanism for passing read-only attributes to React components. These
attributes are usually required to be of certain types or forms for them to be used properly in the
component.
If a prop is passed to a component in a type or form that isn’t expected, the component may not
behave as we intended. Thus, a great way of improving React components is props validation.
propTypes:
React provides an internal mechanism for adding type checking to components. React components
use a special property named propTypes to set up type checking.
PropTypes
When props are passed to a React component, they are checked against the type definition
configured in the propTypes property. When an invalid value is passed for a prop, a warning is
displayed on the JavaScript console.
React.PropTypes:
Prior to React 15.5.0, a utility named PropTypes was available as part of the React package, which
provided a lot of validators for configuring type definitions for component props. It could be
accessed with React.PropTypes.
However, in later versions of React, this utility has been moved to a separate package named prop-
types, so you need to add it as a dependency for your project in order to get access to the
PropTypes utility:
npm install prop-types --save-dev
ReactComponent.propTypes = {
// ...prop type definitions here
};
PropTypes validators:
As stated in the previous section, the PropTypes utility exports a lot of validators for configuring
type definitions. Here are the validators for the basic data types:
PropTypes.any // PropTypes.bool // PropTypes.number //
PropTypes.string // PropTypes.func // PropTypes.array //
PropTypes.object // PropTypes.symbol
Component.propTypes = {
anyProp: PropTypes.any,
booleanProp: PropTypes.bool,
numberProp: PropTypes.number,
stringProp: PropTypes.string,
functionProp: PropTypes.func
};
Multiple types:
PropTypes also exports validators that can allow a limited set of values or multiple sets of data
types for a prop. Here they are:
• PropTypes.oneOf: The prop is limited to a specified set of values, treating it like an enum.
• PropTypes.oneOfType: The prop should be one of a specified set of types, behaving like a
union of types.
Component.propTypes = {
enumProp: PropTypes.oneOf([true, false, 0, "Unknown"]),
unionProp: PropTypes.oneOfType([
PropType.bool,
PropType.number,
PropType.string,
PropType.instanceOf(Person)
])
};
Required props:
Sometimes you need to control your component output, You could do that by conditional rendering.
You can prevent the component from rendering whenever a required prop is not passed or is invalid
and render an alternative output instead using the conditional rendering.
const SimpleComponent = ({ requiredProps }) => {
return (
<>
{requiredProps ? (
<h1>We need this {requiredProps} !</h1>
) : (
<h1>Ooops ! we need that props</h1>
)}
</>
);
};
DOM Events
Let’s remember what’s DOM events:
• Events on the website are interacting on the browser. For example a mouse click, file
loading on the browser or swiping the image left or right.
Handling events with React elements is very similar to handling events on DOM elements. There
are some syntactic differences:
• React events are named using camelCase, rather than lowercase.
• With JSX you pass a function name as the event handler, rather than a string.
We could find many events as onMouseMove, onChange, onCLick and many more.
Events/ Functions
Since we are writing JavaScript, React events are written in camelCase syntax:
onClick instead of onclick.
React event handlers are written inside curly braces:
onClick={handleClick}
const ActionLink = () => {
const handleClick = e => {
e.preventDefault();
console.log("The link was clicked.");
};
return (
<a href="/" onClick={handleClick}>
Click me
</a>
);
};
Events/ Functions
In the example above, the onClick attribute is our event handler, and it is added to the target
element in order to specify the function to be executed when that element is clicked. The onClick
attribute is set to the handleClick function, which alerts a message.
In simpler terms, this means that whenever the button is clicked on, the handleClick function is
called which shows the alert box.
Events/ Functions props
There are many situations when writing React where you’ll want to pass a function as prop.
Usually it’s to pass down to a child component so that the child can notify the parent of some event.
In this example, we passed handleClick function from ActionLink component as props to
ActionComponent.
We wait from ActionComponent to trigger some action , in this case alert a message.
Events/ Functions props test
In ActionComponent, we expect when we click the Click Me! Link to alert a message from
handleClick that defined inside the parent component ActionLink.
As we expected, the alert get triggered and test was successfully passed!
Events/ Conclusion
Handling events is very important aspect to learn.
Since the applications are based on the user interactions, Handling gives us the power to control any
interaction between the user and our application.
React proppose all the DOM events handling that exists, with a little difference in calling them like
the use of the camel case naming.
Is this a valid statement True
onSubmit={handleSubmit}