DEV Community

Cover image for React Component Props
Ben D.
Ben D.

Posted on • Updated on

React Component Props

The most important concepts to understand React are components, props, state and hooks.

I will explain 'props', short for 'properties' here. Props are accessed as parameters in the Component function. Often times, they are destructured to keep the code cleaner.

I will assume that you know how to import and export the components in your project hierarchy but if not, you can check out the create-react-app docs

//in the App.js file you would render the prop:

<Hello person={benjamin} />

//and in the Hello.js file, the person prop would be passed down:

function Hello(props) {
return <h1>Hello, {props.person}</h1>
}

//which would ouput:

<h1>Hello, benjamin</h1>

//alternatively, you could destructure the prop for cleaner code:

function Hello({props}) {
return <h1> Hello,{person}</h1>
}
Enter fullscreen mode Exit fullscreen mode

You can have as many props as needed. For example:

function Weather ({temperature, day} {
return <h2> It will be {temperature} degrees on {day}</h2>
}

<Weather temperature='84' day='Tuesday' />

//Which results in:

<h2> It will be 84 degrees on Tuesday </h2>

Enter fullscreen mode Exit fullscreen mode

Class components

It seems that developers are moving away from class-based components as it's unnecessarily verbose. However, if you are still using class components, the process is very similar, but you need to add a this.props instead of just props

For example:

import { Component } from 'react'

class Greeting extends Component {
  render() {
    return <p>Hello, {this.props.who}!</p>;
  }
}
Enter fullscreen mode Exit fullscreen mode

Prop Types

A prop can have any value including strings, numbers, objects, arrays, booleans, variable, function references.

  • String literal:

<Component prop='this is a string'>

  • Template literal:

<Component prop={`this is a string with a ${variable}`}

  • Number literal:

<Component prop={14} />

  • Boolean literal:

<Component prop={true} /}

  • Object literal:

<Component pro={{property : 'value'}} />

  • Array literal:

<Component prop={['item 1','item 2']} />

  • JSX

<Component prop={Message who='Batman' />} />

  • Variables or function references

<Component prop={functionReference} />

Top comments (0)