DEV Community

loading...

Passing Data Between React Components

Thomas(Tripp) White
Living life one line at a time.
・3 min read

React is a JavaScript library for building user interfaces. React utilizes reusable components. This allows you to reuse your code, control how the components update, and control how they communicate with each other.

Props

Props allows us to pass data between React components. We can pass callback functions and other pieces of data. We can attach multiple props to each component. Passing props and accessing them is very simple. Lets look at some examples.

function Home(){
   return(<div>
      <Greeting/>
   </div>)
}
Enter fullscreen mode Exit fullscreen mode

Above we have a functional component Home that renders a second function component Greeting. Right now this is just a simple render. There is no passing of information between the two components.

Parents and Children

To understand how props work, we must first understand the relationship between parent and children components. React allows you to pass props but only down the family tree. A parent can only pass information to the children. Children can not pass props up to the parent. This is the one way data flow of React. It will always pass props down the component hierarchy unless your use a separate state manager like Redux. Redux is a topic for a different article.

Passing Props

function Home(){
   return(<div>
      //passing name prop to greeting component
      <Greeting name=Tripp/>
   </div>)
}
Enter fullscreen mode Exit fullscreen mode
function Greeting(props){
   return(<div>
    //using prop passed down
    <p>Hi there {props.name}</p>
   </div>
Enter fullscreen mode Exit fullscreen mode

In order to pass a prop to a component all we have to do is name the prop and set it equal to some value. In the example above, we are passing a prop called name that is equal to a string. Passing a prop gives us access to the information in our Greeting component. To access the prop in our functional component we use props.name. (If this was a Class component we would use this.props.name. props.(name of prop being passed) will give us access to our prop just like an argument of a function.

Callbacks

Remember that React is a one way data flow. We can only pass props from parents to children. What if we have some logic that happens in our children component and we want it to change data in our parent component? We can do this by using callback functions. Props allows us to not only pass data but we can also pass functions as a prop. When we use this callback function in our children component it can then preform actions that will effect our parent component.

function Home(){
   //useState establishes state in a functional component
   let [showSecret, setShowSecret] = useState(0)
   return(<div>
      <Greeting name=Tripp displaySecrete={setShowSecret}/>
      {/* will show a message once state is true */}
      {showSecret ? <p>Secret: You just went Against the Flow</p> : <p></p>}
   </div>)
}
Enter fullscreen mode Exit fullscreen mode
function Greeting(props){
   return(<div>
      <p>Hi there {props.name}/>
      {/*clicking button will update state of the parent component and show the secret in the parent component */}
      <button onClick={()=> props.displaySecrete(1)>Show Secret</button>
   </div>)
}
Enter fullscreen mode Exit fullscreen mode

Summary

  • React has a one way data flow. Parent components pass props down to its children. Children components can not pass props up to their parent component.
  • The Passing of callback functions as a prop allows children components to make changes in their parent component.
  • When ever a prop is updated it will trigger a re render.
  • Pass in props when you initialize your component. <Greeting name=‘Tripp’ /> The Prop is called name with the value of ‘Tripp’
  • To access a prop in the the children component: props.name

I hope this short and sweet article on props was helpful. These are simple examples of passing data between components. Once you’ve master this you will be able to quickly enhance the data flow among your components and make more complex applications.

Discussion (7)

Collapse
mizaelpv profile image
Mizael Paredes Vielma • Edited

Prop drilling it could be a real problem, that’s why react team built Context, basically with this hook you can access to any data in your store from anywhere in your app

Collapse
zaklaughton profile image
Zak Laughton

I'd argue this example is nowhere near needing React context.

I usually hear "prop drilling" refer to excessively and deeply passing props, which I don't think is happening in this example. Passing props is actually preferable to Context here, and in most other use cases. Even if you do want to work around prop drilling, it's best to try applying component composition before reaching for Context, as mentioned in the Context React docs.

Context is useful, but it has trade-offs. It's a workaround; not a default container for all state. It should only be used in specific use cases when you have data you want to access in many parts of your app.

Collapse
iq9 profile image
Russell Brooks

Another problem with Context. It's implicit. Props are explicit. Context isn't easily discoverable, in code, in the traditional ways. In this code I’m in, we have this line.

const { currentActiveLink } = useContext(NavigationContext);
Enter fullscreen mode Exit fullscreen mode

That’s clearly the “Consumer” side of this communication (the “Get” side). How does one find, in code, the Producer side ("set" side)?

For 100% of developers, the traditional way to discover that, is to do global searches for 3 things you see on the line above: currentActiveLink, useContext, and NavigationContext. I do that, and I get 0 results - nothing is setting that value. (Undiscoverable React magic, exactly like Active Record’s magic methods.) When I was first learning React, this baffled me for months. The React docs just tell you what Context is, but give you no clear examples on the Setting and Consuming of Context. So even after reading them, I still had no idea what to "grep" for. Probably another reason why the React docs also advise against using Context.

Props, by contrast, 100% explicit. Easily findable in code by simply doing searches for those attributes:

<Welcome userName="sara" />
Enter fullscreen mode Exit fullscreen mode

Do a Find for "userName", and you'll immediately see the code where that userName was set.

Collapse
bennypowers profile image
Benny Powers 🇮🇱🇨🇦

React utilizes reusable components. This allows you to reuse your code,

But it doesn't allow others to reuse your code unless they buy into the react silo

This is why if you're publishing components, you should not publish them as react components, but custom elements instead.

Every framework except react (including preact) supports custom elements, and if you are stuck with react, you can use a wrapper to add support.

You might think it looks good on a resume now, but in a few years you'll be stuck with framework skills instead of web skills.

If you like the react API, use preact, but if you're writing reusable components, publish web components.

Collapse
xamian profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Xamian

Shameless self promotion.

Collapse
xamian profile image
Xamian

Content is fine, but the header suggests a somewhat different article. The usecase where different components on same level (siblings) need to "talk" to each other is not touched here, only parent/child passing.

Collapse
itays123 profile image
Itay Schechner

A great post for beginners! I remember when I used to struggle with this. Liking to raise popularity.