Member-only story

How to pass data to React components

Kristijan
2 min readMay 10, 2020

--

Passing data to child components is something we often do in React. It is part of it and helps us to organize our code better. In this post, I am covering how to use them in both functional and class components.

React logo

Passing props

No matter what type of component you use, sending props is always the same. We are using components XML tags, and props as its attributes.

<SomeComponent
hardcodedProps=”some text”
expressionProp={“expression “ + 1}
/>

Using props in functional component

The simplest way of using props is in the functional component. All the props are part of the first argument of that component function.

function SomeComponent (props) {
console.log(props.hardcodedProps); // “some text”
console.log(props.expressionProp); // “expression 1”
return <div>Some Component</div>
}

Using props in the class component

Using props in class components can look a bit more complicated, but it is still quite straightforward. Each instance of a class has this, and the general rule is that props are bound to it.

class SomeComponent extends PureComponent {
render() {
console.log(this.props.hardcodedProps); // “some text”
console.log(this.props.expressionProp); //…

--

--

No responses yet