Dmitri Borohhov
Dmitri Borohhov

Reputation: 1603

Pass data to React (Native) hooks like class-based components

I'm just starting transitioning to Hooks in React Native, and I have a hard time passing data to child elements. With class-based components, we could do a very simple XML-style passing of props.

Example with classes

class Parent extends React.Component {
    render() {
        return (
            <Child data={"Hello"}/>
        )
    }
}

And the child:

class Child extends React.Component {
    render() {
        return (
            <Text>{this.props.data}</Text>
        )
    }
}

Example with Hooks:

When using a hook, I was able to pass data via:

<Child {...["Hello"]} />

The hook would look like:

export const Child = (data) => {
    return (
        <Text>{data[0]}</Text>
    )
}

Is there a way to refactor just the child classes into hooks and leave calls to these elements untouched (<Child data={"Hello"}/> ) ?

Upvotes: 0

Views: 1276

Answers (2)

Idan
Idan

Reputation: 5450

You are just missing a small step:

export const Child = (data) => {... 

should be:

export const Child = (props) => {... 
  const {data} = props

or:

export const Child = ({data}) => {..

Upvotes: 1

norbitrial
norbitrial

Reputation: 15166

I guess if you leave as <Child data={"Hello"}/> in your parent component and refactoring Child component with hooks, you can access the data just like the following:

export const Child = ({data}) => {
   return (
      <Text>{data}</Text>
   )
}

Technically props has been passed to your component as const Child = (props) => {}. Once you destructure props, you could have the data property as above.

It's called object destructuring, read further here.

I hope that helps!

Upvotes: 2

Related Questions