LayTexas
LayTexas

Reputation: 645

Is there any way to use the props outside the component?

I need to pass a duck to my component to do a search on redux. How can I pass this duck as "props"?

My Screen

import React from 'react'
const MyScreen: React.FC<IProps> = (props) => {

    return (
        <Component
            navigation={props.navigation}
            duck={MyDuck}
        />
    );
}

My Component

import React from 'react'
    const MyComponent: React.FC<IProps> = (props) => {
    const {duck} = props;
    
        return (
            <View/>
        );
    }

function mapDispatchToProps(dispacth) {
    return {
        //I need to use the prop here in this place
        register: duck.mapDispatchToProps(dispacth),
    };
}

Upvotes: 0

Views: 175

Answers (2)

Linda Paiste
Linda Paiste

Reputation: 42218

You can access the props using the second argument of mapDispatchToProps which is ownProps -- the props passed to the component.

function mapDispatchToProps(dispatch, ownProps) {
  const duck = ownProps.duck;
...

or just

function mapDispatchToProps(dispatch, {duck}) {

But the question that you are asking is not going to make this code work. The duck prop is a component MyDuck which does not have a mapDispatchToProps property. mapDispatchToProps is an argument to the connect higher-order component. It is not a property.

I don't understand what you are trying to do here but you will need to approach it a different way.

Upvotes: 1

navintellis
navintellis

Reputation: 59

There is a optional mergeProps callback available as third argument in connect which follows the below format

(stateProps, dispatchProps, ownProps) =>
    ({ ...stateProps, ...dispatchProps, ...ownProps })

stateProps - are all the props from mapToState callback dispatchProps - are all the props from mapDispatchToProps callback ownProps - are all the props that are passed down to the component like <Button foo={'bar'} />

you will be able to access the desired duck prop in the ownProps argument

reference - https://www.emgoto.com/redux-access-props-mapdispatchtoprops/

Upvotes: 0

Related Questions