Reaction props

How to use props to pass data around React components

Props are how a component obtains its properties. Starting from the top component, each child component gets its props from the parent component. In functional components, props are all the elements that are passed, and they can be added by addingpropsAs a function parameter:

const BlogPostExcerpt = props => {
  return (
    <div>
      <h1>{props.title}</h1>
      <p>{props.description}</p>
    </div>
  )
}

In class components, props are passed by default. No need to add any special content, they can be accessed in the following waysthis.propsIn the Component instance.

import React, { Component } from 'react'

class BlogPostExcerpt extends Component { render() { return ( <div> <h1>{this.props.title}</h1> <p>{this.props.description}</p> </div> ) } }

Passing props to child components is a great way to pass values in an application. Components either hold data (have state) or receive data through their props.

It becomes complicated in the following situations:

  • You need to access the state of the component from the children several levels down (all previous children need to act as transfer objects, even if they don’t need to know the state, it’s complicated)
  • You need to access the state of the component from completely unrelated components.

Default value of props

If you don't need any value, if the default value is missing when you initialize the component, you need to specify a default value for it.

BlogPostExcerpt.propTypes = {
  title: PropTypes.string,
  description: PropTypes.string
}

BlogPostExcerpt.defaultProps = { title: ‘’, description: ‘’ }

Some tools, such asESLintAbility to force the definition of defaultProps for some components that do not explicitly require propTypes.

How to pass the props

When initializing the component, pass the props in a way similar to HTML attributes:

const desc = 'A description'
//...
<BlogPostExcerpt title="A blog post" description={desc} />

We pass the title as a pure string (you canas long asProcess strings! ), and use the description as a variable.

children

A special prop ischildren. Included inbodyThe name of the component, for example:

<BlogPostExcerpt title="A blog post" description="{desc}">
  Something
</BlogPostExcerpt>

under these circumstancesBlogPostExcerptWe can access "something" by looking upthis.props.children.

Although props allow a component to receive properties from its parent object, such as being "instructed" to print some data, the state allows the component to take on its own life and be independent of the surrounding environment.

Download mine for freeResponse Handbook


More response tutorials: