Ofir Hadad
Ofir Hadad

Reputation: 1900

Using React props vs import , What is the best choice?

I'm trying to understand what is the best way to use props in React

Let's say I have a container that use import {FormattedMessage} from 'react-intl'

And let say I have a component used in the JSX of the container.

Now, If I wanted to use FormattedMessage in the component also, Should I use import again in the component? or should I send FormattedMessage as a prop to the component via the container?

Example:

import {FormattedMessage} from 'react-intl';

class Container {
   render() {
        return (
                <Component formattedMessage={FormattedMessage} />
        );
   }
}

Upvotes: 4

Views: 1241

Answers (2)

kngroo
kngroo

Reputation: 462

<FormattedMessage/> is a standalone component and passing it down to you child components in that manner completely unnecessary.

If you want to pass components from parent to child, use the special prop children instead.

<Container> render function:

return (<Component><FormattedMessage /></Component>)

<Component> render function:

return (<div>{props.children}</div>)

see: https://reactjs.org/docs/composition-vs-inheritance.html

Note: If you want to send the translated string into your child component as a prop, use injectIntl higher order component to pass the intl prop into your component. You can then call intl.formatMessage({id, defaultMessage}) from within your component to translate the string you want to pass as a prop into your child component.

see: https://github.com/yahoo/react-intl/wiki/API#injection-api

Upvotes: 3

bitwikinger
bitwikinger

Reputation: 264

You should try to not using props to transfer Components to other Components. Better import them where you need them or use Higher Order Components instead. Props are usually used to transfer data or container functions.

Upvotes: 1

Related Questions