Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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} />
        );
   }
}
like image 660
Ofir Hadad Avatar asked Nov 03 '25 11:11

Ofir Hadad


2 Answers

<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

like image 199
kngroo Avatar answered Nov 06 '25 02:11

kngroo


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.

like image 22
bitwikinger Avatar answered Nov 06 '25 04:11

bitwikinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!