React programming Examples (State and Props)
React programming Examples (State and Props)
February 16, 2021

React is a JavaScript library for building user interfaces. The practice is important to understand react JS. Here are some important JavaScript React programming Examples.
React Online Playgrounds
If you’re interested in playing around with React, you can use an online code playground. Try a React Programming Examples on CodePen, CodeSandbox, or Stackblitz.
React programming Example #1: props
- Props are arguments passed into React components.
- Props are passed to components via HTML attributes.
- They are like function arguments in JavaScript and attributes in HTML.
import React, { Component } from "react"; export class HelloMessage extends Component { constructor(props) { super(props); console.log(props); this.state = {}; } render() { return <div>Hello {this.props.name}</div>; } } export default HelloMessage;
Program #2: React state
React components has a built-in state object. The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders.
import React, { Component } from "react"; export class Timer extends Component { constructor(props) { super(props); console.log(this); this.state = { seconds: 0 }; } tick() { this.setState((state) => ({ seconds: state.seconds + 1, })); console.log(this.state.seconds); } componentDidMount() { this.interval = setInterval(() => this.tick(), 1000); } componentWillUnmount() { clearInterval(this.interval); } render() { return <div>Seconds: {this.state.seconds}</div>; } } export default Timer;
class Car extends React.Component{ constructor(props){ super(props); this.state = { brand: "BMW", color: "black" } } }
class Car extends React.Component { constructor(props) { super(props); this.state = { brand: "BMW", color: "Black" }; } changeColor() { this.setState(prevState => { return { color: "Red" }; }); } render() { return ( <div> <button onClick={() => this.changeColor()}>Change Color</button> <p>{this.state.color}</p> </div> ); } }
<Car brand="Mercedes"/>
class Car extends React.Component { constructor(props) { super(props); this.state = { brand: this.props.brand, color: "Black" }; } }
function Car(props) { let [brand, setBrand] = useState(props.brand); }
function Person(props) { // We are declaring a state variable called name. // setName is a function to update/change the value of name let [name, setName] = useState(''); }
Props | State |
---|---|
Immutable | Owned by its component |
Has better performance | Locally scoped |
Can be passed to child components | Witeable/Mutable |
has setState() method to modify properties | |
Changes to state can be asynchronous | |
can only be passed as props |