forked from kay-is/react-from-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
06-property-types.html
51 lines (38 loc) · 1.42 KB
/
06-property-types.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!doctype html>
<title>06 Property Types - React From Zero</title>
<script src="https://unpkg.com/[email protected]/dist/react.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script src="https://unpkg.com/[email protected]/browser.min.js"></script>
<div id="app"></div>
<script type="text/babel">
// Components get created to encapsule stuff
// that should be together in one place and for reuse
// Reuse requires the user of the component to supply the correct properties
// So we can define a type of each property and set defaults
function MyComponent(props) {
return (
<div className={props.className}>
<h1>Hello</h1>
<h2>{props.customData}</h2>
</div>
)
}
// Add the propTypes (function-)property to the component function
// to let in validate its (element-)properties
MyComponent.propTypes = {
// React supplies us with a bunch of types, like string
customData: React.PropTypes.string,
}
// Add defaultProps (function-)property to set the defaults
// if nothing was provided by the user
MyComponent.defaultProps = {
customData: 'default',
className: 'default-class',
}
// This will show a warning in the console, because customData should be a string
var reactElement = <MyComponent customData={123}/>
// This will use the defaults
reactElement = <MyComponent/>
var renderTarget = document.getElementById('app')
ReactDOM.render(reactElement, renderTarget)
</script>