Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context in "stateless" component?

Tags:

reactjs

I have the following code in a component and I would like a stateless component to access this part of code:

Main component:

function createApp(store, communityIds) {
const App = React.createClass({

    childContextTypes: {
        localizedString: React.PropTypes.func,
    },

    getChildContext: function() {
        return {
            localizedString: function(key, fallback) {
                return getKey(key, fallback);
            },
        };
    },

    render: function() {
        return (
            <Provider store={store}>
                <Client communityIds={communityIds}/>
            </Provider>
        );
    },
});

return <App/>;
}

Stateless:

export default () => (dispatch, getState) => {
    const state = getState();

    const token = state.user.get('token');

    if (!token) {
        throw new Error('test'); // this.context.localizedString does not work
    }
}
like image 869
Jorge Costa Avatar asked Mar 08 '16 11:03

Jorge Costa


People also ask

What is the component of context?

Component context provides a way to implicitly share values like these between components without having to explicitly pass a prop through every level of the tree. CKComponentContext values are NOT expected to change between component generations.

Can we use context in functional component?

context; and that allows you to access your context outside of the JSX. Or instead, you could put in static contextType = ColorContext; . This works pretty good for class-based components since it simplifies how to bring your context into your component. But, it will not work in a functional component.

What are the stateless components?

Stateless components are those components which don't have any state at all, which means you can't use this. setState inside these components. It is like a normal function with no render method. It has no lifecycle, so it is not possible to use lifecycle methods such as componentDidMount and other hooks.

What is context in React?

Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language. For example, in the code below we manually thread through a “theme” prop in order to style the Button component: class App extends React.


4 Answers

What you have provided under your definition of "Stateless:" function is not what a Stateless function is. You have provided your action creator as a thunk. I assume you wanted to insert the code for your Client component instead. To access context in a stateless component, your Client component would do something like this (which is documented here)

const Client = (props, context) => {   
    return  <div >{context.localizedString("someKey", "someFallback")} </div>
}

Client.contextTypes = {
    localizedString: React.PropTypes.func
}

export default Client
like image 198
SlimSim Avatar answered Oct 01 '22 08:10

SlimSim


I had the same question. The modern way (in 2019) is to use hook useContext(contextName). Docs: https://reactjs.org/docs/hooks-reference.html#usecontext

  const dumbComp = (props) => { 
       const context = useContext(contextName);
          return(
             <div>
             ...
          </div>
       );
    }
like image 34
Dm Mh Avatar answered Oct 01 '22 08:10

Dm Mh


Use second parameter of stateless component

const MyStatelessComponent = (props, context) => { 
   const onGoButtonClick = () => {
      context.router.push('https://www.google.co.in');
   };

   return(
      <div>
         <button onClick={() => onButtonClick()}>
            {props.buttonName}
         </button>
      </div>
   );
}

MyStatelessComponent.propTypes = {
   buttonName: PropTypes.string.isRequired,
};

MyStatelessComponent.contextTypes = {
   router: React.PropTypes.object.isRequired,
};

export default MyStatelessComponent;
like image 21
Nikhil Mahirrao Avatar answered Oct 01 '22 08:10

Nikhil Mahirrao


Another solution is a self invoking function:

export default (Component=>(
  Component.contextTypes = {
    localizedString: React.PropTypes.func
  }) && Component
)((props, context)=>{
  return  <div>{context.localizedString("someKey", "someFallback")}</div>
})

Or if you define the contextTypes separately to reuse it, you could do:

//addContextTypes.js
export default function(Component){
  return (Component.contextTypes = {
    localizedString: React.PropTypes.func
  }) && Component
}

//component.jsx
import addContextTypes from './addContextTypes'
export default addContextTypes((props, context)=>{
  return  <div>{context.localizedString("someKey", "someFallback")}</div>
})
like image 20
brunettdan Avatar answered Oct 01 '22 09:10

brunettdan