1class MyComponent extends React.Component{
2 constructor(props){
3 super(props);
4 };
5 render(){
6 return(
7 <div>
8 <h1>
9 My First React Component!
10 </h1>
11 </div>
12 );
13 }
14};
15
1// convert a class component to a functional component
2class MyComponent extends React.Component {
3 state: {
4 name: 'Bob'
5 }
6 render() {
7 return (
8 <p>Hello, my name is {this.state.name}</p>
9 );
10 }
11}
12
13const MyComponent = () => {
14 const [name, setName] = React.useState('Bob');
15 return (<p>Hello, my name is {name}</p>);
16}
1class MouseTracker extends React.Component {
2 constructor(props) {
3 super(props);
4 this.handleMouseMove = this.handleMouseMove.bind(this);
5 this.state = { x: 0, y: 0 };
6 }
7
8 handleMouseMove(event) {
9 this.setState({
10 x: event.clientX,
11 y: event.clientY
12 });
13 }
14
15 render() {
16 return (
17 <div style={{ height: '100vh' }} onMouseMove={this.handleMouseMove}>
18 <h1>Move the mouse around!</h1>
19 <p>The current mouse position is ({this.state.x}, {this.state.y})</p>
20 </div>
21 );
22 }
23}
1//Render props are functions that are passed to props as values
2const User = (props) => {
3 const [name, setName] = useState('John')
4
5 //we pass values to prop-function as args
6 return <div>{props.render(name)}</div>
7}
8
9//Then we can use this component like this:
10<div>
11 //when using the component we receive the passed values (name) as args here
12 <User render={(name) => <div>{name}</div>} />
13</div>
14
15
1/* PASSING THE PROPS to the 'Greeting' component */
2const expression = 'Happy';
3<Greeting statement='Hello' expression={expression}/> // statement and expression are the props (ie. arguments) we are passing to Greeting component
4
5/* USING THE PROPS in the child component */
6class Greeting extends Component {
7 render() {
8 return <h1>{this.props.statement} I am feeling {this.props.expression} today!</h1>;
9 }
10}
11
12--------------------------------------------
13function Welcome(props) {
14 return <h1>Hello, {props.name}</h1>;
15}
16
17const element = <Welcome name="Sara" />;
18ReactDOM.render(
19 element,
20 document.getElementById('root')
21);
1function Welcome(props) { return <h1>Hello, {props.name}</h1>;
2}
3
4const element = <Welcome name="Sara" />;ReactDOM.render(
5 element,
6 document.getElementById('root')
7);