I am coming from a vue.js background and I have just recently started looking into react.
I have a component: PageContent.jsx and I wish to use it without constantly having to import it to be able to use it inside the render function (JSX).
In vue it is possible to globalise a component using:
Vue.component(componentName, componentObject)
Is there anything similar in react?
Hmm, there isn't any kind of "global" component in React. Each component has to be imported or passed as a prop. You have a few options if you want to avoid adding an import to each file though:
1) Create a Higher Order Component that renders the PageContent and the wrapped component.
import PageContent from './PageContent';
const withPageContent = WrappedComponent => {
return class extends React.Component {
render () {
return (
<PageContent>
<WrappedComponent />
</PageContent>
)
}
}
};
export default withPageContent;
// Usage
import withPageContent from './withPageContent';
class MyComponent extends React.Component {
render () {
return (
<div>
I'm wrapped in PageContent!
</div>
)
}
}
export default withPageContent(MyComponent);
2) Pass PageContent as a prop to a component:
import PageContent from './PageContent';
export default class App extends React.Component {
render() {
return (
<React.Fragment>
<Child1 content={PageContent} />
<Child2 content={PageContent} />
</React.Fragment>
)
}
}
// Usage
export default class Child1 extends React.Component {
render () {
const PageContent = this.props.content;
return (
<PageContent>
I'm wrapped in PageContent!
</PageContent>
)
}
}
export default class Child2 extends React.Component {
render () {
const PageContent = this.props.content;
return (
<PageContent>
I'm wrapped in PageContent!
</PageContent>
)
}
}
I very much agree with Chase's answer.
Still if you need another approach you can use the context api. You can declare in the App root, or another nested components tree, a collection of components that you want to easily access.
Here is an example with the useContext hook, but hooks is not a must. The structure is the standard create-react-app structure.
The component we would like to access globally - src/deep/Header.js:
function Header() {
return (
<h1>
I am a global component
</h1>
);
}
export default Header;
The context creation - src/global-components-context.js:
import React from 'react';
const MyContext = React.createContext(null);
export default MyContext;
The grouping of the global-components - src/global-components.js:
import Header from './deep/Header';
const contextValue = {
Header,
};
export default contextValue;
The app init file - src/index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import MyContext from './global-components-context';
import contextValue from './global-component';
ReactDOM.render(
<MyContext.Provider value={contextValue}>
<App />
</MyContext.Provider>,
document.getElementById('root')
);
Using the component without importing it - src/App.js:
import { useContext } from 'react';
import globalComponent from './global-components-context';
function App() {
const Context = useContext(globalComponent);
return (
<div className="App">
<Context.Header />
</div>
);
}
export default App;
I think this is the most global components you can have in react. Note that you still need to import the context wherever you would like to use a global component.
Also one more disclaimer, global components are very hard to test and often to reason about. I believe that is why there is no standard solution for it in react.
Hope I could help
Related
I was trying to get the queries from my url pattern like localhost:3000/post?loc=100 by using useRouter() from "next/router" and fetching some data using that id from my server. It worked when I used it in a Stateless Functional Component.
But the page showing "Invalid hook call" then. I tried calling getInitalProps() of a Stateless Functional Component, but it didn't work there either and showed the same error.
Is there any rule to use this method?
I was developing a front-end using React Library and Next.js Framework.
constructor(props) {
this.state = {
loc: useRouter().query.loc,
loaded: false
};
}
Hooks can be used only inside functional components, not inside classes. I would recommend to use withRouter HOC as per next.js documentation:
use the useRouter hook, or withRouter for class components.
Or see From Classes to Hooks if you want to switch to hooks.
In general, it's possible to create a wrapper functional component to pass custom hooks into class components via props (but not useful in this case):
const MyClassWithRouter = (props) => {
const router = useRouter()
return <MyClass {...props} router={router} />
}
class MyClass...
constructor(props) {
this.state = {
loc: props.router.query.loc,
loaded: false
};
}
withRouter example
https://stackoverflow.com/a/57029032/895245 mentioned it, but a newbie like me needed a bit more details. A more detailed/direct description would be:
Function component:
import { useRouter } from "next/router";
export default function Post() {
const router = useRouter();
return (
<div>{ router.query.id }</div>
)
}
Class component equivalent:
import { withRouter } from 'next/router'
import React from "react";
export default withRouter(class extends React.Component {
render() {
return (
<div>{ this.props.router.query.id }</div>
)
}
})
I tested this out more concretely as follows. First I took vercel/next-learn-starter/basics-final/pages/posts/[id].js and I hacked it to use the router:
diff --git a/basics-final/pages/posts/[id].js b/basics-final/pages/posts/[id].js
index 28faaad..52954d3 100644
--- a/basics-final/pages/posts/[id].js
+++ b/basics-final/pages/posts/[id].js
## -4,13 +4,17 ## import Head from 'next/head'
import Date from '../../components/date'
import utilStyles from '../../styles/utils.module.css'
+import { useRouter } from "next/router"
+
export default function Post({ postData }) {
+ const router = useRouter();
return (
<Layout>
<Head>
<title>{postData.title}</title>
</Head>
<article>
+ <div>router.query.id = {router.query.id}</div>
<h1 className={utilStyles.headingXl}>{postData.title}</h1>
<div className={utilStyles.lightText}>
<Date dateString={postData.date} />
Then, I ran it as:
git clone https://github.com/vercel/next-learn-starter
cd next-learn-starter
git checkout 5c2f8513a3dac5ba5b6c7621d8ea0dda881235ea
cd next-learn-starter
npm install
npm run dev
Now when I visit: http://localhost:3000/posts/ssg-ssr I see:
router.query.id = ssg-ssr
Then I converted it to the class equivalent:
import Layout from '../../components/layout'
import { getAllPostIds, getPostData } from '../../lib/posts'
import Head from 'next/head'
import Date from '../../components/date'
import utilStyles from '../../styles/utils.module.css'
import { withRouter } from 'next/router'
import React from "react"
export default withRouter(class extends React.Component {
render() {
return (
<Layout>
<Head>
<title>{this.props.postData.title}</title>
</Head>
<article>
<div>router.query.id = {this.props.router.query.id}</div>
<h1 className={utilStyles.headingXl}>{this.props.postData.title}</h1>
<div className={utilStyles.lightText}>
<Date dateString={this.props.postData.date} />
</div>
<div dangerouslySetInnerHTML={{ __html: this.props.postData.contentHtml }} />
</article>
</Layout>
)
}
})
export async function getStaticPaths() {
const paths = getAllPostIds()
return {
paths,
fallback: false
}
}
export async function getStaticProps({ params }) {
const postData = await getPostData(params.id)
return {
props: {
postData
}
}
}
and everything seemed to be unchanged.
Tested on Next.js 10.2.2.
I'm setting up ContextApi for the first time in a production app, hoping to replace our current handling of our app configs with it. I've followed the official docs and consulted with similar issues other people are experiencing with the API, and gotten it to a point where I am able to correctly the config when I do Config.Consumer and a callback in render functions. However, I cannot get this.context to return anything other than an empty object.
Ideally, I would use this.context in lifecycle methods and to avoid callback hell, so help would be appreciated. I've double checked my React version and that I'm setting the contextType. Below is a representation of the code
config.js
import { createContext } from "react";
export default createContext();
index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { Router, browserHistory } from "react-router";
import { syncHistoryWithStore } from "react-router-redux";
import Config from "../somePath/config";
// more imports
function init() {
const config = getConfig();
const routes = getRoutes(config);
const history = syncHistoryWithStore(browserHistory, appStore);
ReactDOM.render(
<Provider store={appStore}>
<Config.Provider value={config}>
<Router history={history} routes={routes} />
</Config.Provider>
</Provider>,
document.getElementById("app")
);
}
init();
someNestedComponent.js
import React, { Component } from "react";
import { connect } from "react-redux";
import Config from "../somePath/config";
#connect(
state => ({
someState: state.someState,
})
)
class someNestedComponent extends Component {
componentDidMount() {
console.log(this.context);
}
render() {
return (...someJSX);
}
}
someNestedComponent.contextType = Config;
export default someNestedComponent;
Currently running on:
React 16.8.6 (hopi to see error messages about circuitous code but
didn't get any warnings)
React-DOM 16.7.0
React-Redux 6.0.1
The problem is that someNestedComponent doesn't refer to the class where this.context is used:
someNestedComponent.contextType = Config;
It refers to functional component that wraps original class because it was decorated with #connect decorator, it is syntactic sugar for:
const someNestedComponent = connect(...)(class someNestedComponent extends Component {
...
});
someNestedComponent.contextType = Config;
Instead, it should be:
#connect(...)
class someNestedComponent extends Component {
static contextType = Config;
componentDidMount() {
console.log(this.context);
}
...
}
There are no callback hell problems with context API; this is conveniently solved with same higher-order component pattern as used in React Redux and can also benefit from decorator syntax:
const withConfig = Comp => props => (
<Config.Consumer>{config => <Comp config={config} {...props} />}</Config.Consumer>
);
#connect(...)
#withConfig
class someNestedComponent extends Component {
componentDidMount() {
console.log(this.props.config);
}
...
}
You didn't use a consumer to get the values
ref: https://reactjs.org/docs/context.html#contextconsumer
Function components do not support contextType.
I encountered an issue when trying to add context to a React component that was wrapped with a React Router withRouter(...) function.
import React, { Component } from 'react'
import UserContext from './UserContext'
class Toolbar extends Component {
render(){
return (
<div>username: this.context.username</div>
)
}
}
Toolbar.contextType = UserContext
export default withRouter(Toolbar)
The solution to this issue is simply switch the last two lines like so:
export default withRouter(Toolbar)
Toolbar.contextType = UserContext
My component is defined as follows:
import React, { Component } from "react";
import HOCName from "./HOCName";
class Hello extends Component {
render() {
return <h1>{this.props.name}</h1>;
}
}
export default HOCName(Hello);
MY HOC is defined as follows:
import React from "react";
export default WrappedComponent => props => {
const age = 23;
return (
<div>
<WrappedComponent {...props} age={age} />
<button>say Hello</button>
</div>
);
};
My question is how can I retrieve my button in my Component "Hello" ?
Thanks in advance for your help
You can choose one of the solutions
Pass button as a child of the passed component
Pass the button as a prop to the WrappedComponent
Here is an example of the two solutions
https://codesandbox.io/s/96q5ll9k4
I have a react component and I want to import a long JSX code into it. However, the JSX has variables which include this.state.example in it. How do I import this?
Here's an example:
class CompA extends Component {
state={displaying:false}; render(){const {displaying}=this.state; return({x})}
}
export this file into the top one?
export const x = (
<div>displaying</div>
)
Make x as stateless child component.
//x.jsx
export const X = ({displaying})=>(
<div>{displaying}</div>
)
import {X} from "./x.jsx";
class CompA extends Component {
state={displaying:false};
render(){
const {displaying}=this.state;
return <X displaying={displaying}/>
}
}
X should be a "dummy" or functional ( as they are called ) React component:
const X = ({displaying}) => (
<div> {displaying} </div>
);
So the external file would be like this:
import React from 'react';
const X = ({displaying}) => (
<div> {displaying} </div>
);
export { X };
The X component can be now called normally as any other react component, for example:
<X displaying="This is the text displayed" />
Now you can import it like this:
import { X } from './pathToJSFile'
And use it in your component:
class CompA extends Component {
constructor(props) {
super(props);
this.state.displaying = false;
}
render() {
return(
<X displaying={this.state.displaying} />
);
}
}