Tutorials/React/GET STARTED
Lesson

React Props

GET STARTED/React

React Props

  • Props are data passed to components

  • Props means properties

How to Pass Props

javascript
<Car brand="Ford" />

Receive Props in Component

javascript
function Car(props) {
  return <h2>{props.brand}</h2>
}

Props like Function Arguments

  • Props work like function arguments

  • Data is passed from parent to child

Multiple Props

javascript
<Car brand="Ford" model="Mustang" color="red" />
javascript
function Car(props) {
  return <h2>{props.brand} {props.model}</h2>
}

Different Data Types

String

javascript
<Car name="Ford" />

Number

javascript
<Car year={1969} />

Variable

javascript
let x = "Ford"
<Car brand={x} />

Object Props

javascript
const car = { name: "Ford", model: "Mustang" }

<Car carinfo={car} />
javascript
function Car(props) {
  return <h2>{props.carinfo.name}</h2>
}

Array Props

javascript
const data = ["Ford", "Mustang"]

<Car carinfo={data} />
javascript
function Car(props) {
  return <h2>{props.carinfo[0]}</h2>
}

Props Between Components

javascript
function Garage() {
  return <Car brand="Ford" />
}

React Destructuring Props

  • Destructuring means getting values directly from props

  • No need to write props.color again and again

Basic Destructuring

javascript
function Car({ color }) {
  return <h2>{color}</h2>
}

Destructuring Inside Component

javascript
function Car(props) {
  const { brand, model } = props
  return <h2>{brand} {model}</h2>
}

Rest Operator

javascript
function Car({ brand, color, ...rest }) {
  return <h2>{brand} {rest.model}</h2>
}

rest stores remaining props

Default Values

javascript
function Car({ color = "blue", brand }) {
  return <h2>{color} {brand}</h2>
}

If value not passed then default is used

React Props Children

props children is used to pass content between component tags

javascript
function Card(props) {
  return <div>{props.children}</div>
}

How to Use

javascript
<Card>
  <p>Hello World</p>
</Card>

Content inside Card will be shown using props.children

Example with Components

javascript
function Son(props) {
  return (
    <div>
      <h2>Son</h2>
      {props.children}
    </div>
  )
}
javascript
<Son>
  <p>This is from parent</p>
</Son>
  • Parent sends content

  • Child receives using props.children

React Props | React | Softcrayons Tech Solutions