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} />
);
}
}
Related
I am trying to get adaptValue from Component1 and use it in Component2. For some reason this does not work since my adaptValue is always null/undefined. Is it because Parent is a functional component?
const Parent = (props) => {
const [adaptValue, setAdapt] = useState(null);
return (
<div>
<Component1 setAdapt={setAdapt}/>
<Component2 adaptValue={adaptValue}/>
</div>
)
}
export default class Component1 extends Component {
constructor(props) {
super(props);
}
adaptValue = (value) =>{
DO_SOMETHING_WITH_VALUE
}
componentDidMount() {
this.props.setAdapt(this.adaptValue);
}
render() {
return something;
}
}
export default class Component2 extends Component {
constructor(props) {
super(props);
}
someFunction = (value) =>{
...
//adaptValue is always undefined
this.props.adaptValue(value)
...
}
render() {
return something;
}
}
UPDATE Made the parent a class component in the end and all works. Wondering whether this is a compatibility issue between functional or class-based components.
When passing setAdapt to Component1 ... setAdapt is already a function. There is no need to wrap it in another one. Component1 will modify the value, and Component2 will display it. Function Components have nothing to do with the behavior.
Try ...
App.js
import React, { useState } from "react";
import "./styles.css";
import Component1 from "./Component1";
import Component2 from "./Component2";
export default function App() {
const [adaptValue, setAdapt] = useState(null);
return (
<div>
<Component1 setAdapt={setAdapt} />
<Component2 adaptValue={adaptValue} />
</div>
);
}
Component1.js
import React, { Component } from "react";
export default class Component1 extends Component {
handleClick = () => {
this.props.setAdapt("New Value");
};
render() {
return <button onClick={() => this.handleClick()}>Set Value</button>;
}
}
Component2.js
import React, { Component } from "react";
export default class Component2 extends Component {
render() {
return !!this.props.adaptValue ? (
<h1>{`"${this.props.adaptValue}" <- Value of adaptValue`}</h1>
) : (
<h1>adaptValue Not Assigned</h1>
);
}
}
Sandbox Example ...
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 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
I am following this guide to try and write a React Higher Order Component.
I am trying to have a reusable window component that will act as a container for other components, providing style and behaviour.
I am testing it with a Player component that for now just returns a ReactPlayer component from the npm package react-player
import React, { Component } from 'react';
function Window(WrappedComponent){
return class extends Component{
render(){
return (
<div className="window">
<WrappedComponent/>
</div>
);
}
}
}
export default Window();
This is the code for the player component
import React, { Component } from 'react';
import ReactPlayer from 'react-player';
import Window from './Window.js'
class Player extends Component {
render () {
return <ReactPlayer url='https://www.youtube.com/watch?v=iIKKvG0_KdM' playing />
}
}
const PlayerWindow = Window(Player);
export default PlayerWindow;
change export default Window(); to export default Window;
Remove the brackets from export default Window();
Alternatively, when calling the function you could write
> export const Window = function Window(WrappedComponent){
> return class extends Component{
> render(){
> return (
> <div className="window">
> <WrappedComponent/>
> </div>
> );
> }
> }
> }
For example, a component like this:
import React, { Component } from 'react';
import BodyContent from './BodyContent';
import BottomOne from './BottomOne';
import BottomTwo from './BottomTwo';
class App extends Component {
render() {
return (
<div className="App">
<BodyContent />
<BottomOne />
</div>
);
}
}
export default App;
I want to implement a function on BodyContent that unmount BottomOne and mounts BottomTwo instead, so when I activate the function, the code is reestructured to this:
import React, { Component } from 'react';
import BodyContent from './BodyContent';
import BottomOne from './BottomOne';
import BottomTwo from './BottomTwo';
class App extends Component {
render() {
return (
<div className="App">
<BodyContent />
<BottomTwo />
</div>
);
}
}
export default App;
I'm very new to React, so if there's a better way to do it, I'm open to suggestions, but I really need that end result, a function on BodyContent that unmounts BottomOne and mounts BottomTwo.
You can maintain a state which tells which component to render. Something roughly like this
import React, { Component } from 'react';
import BodyContent from './BodyContent';
import BottomOne from './BottomOne';
import BottomTwo from './BottomTwo';
class App extends Component {
changeBottomComponent = (comp) => {
this.setState({ showBottom: comp})
}
render() {
return (
<div className="App">
<BodyContent changeBottomComponent={this.changeBottomComponent}/>
{this.state.showBottom === 1 ? <BottomOne /> : <BotttomTwo />}
</div>
);
}
}
export default App;
To achieve that maintain a state variable in parent component (some kind of identifier for component) and use that state variable to render different component.
Along with that you also need to pass a function from parent to child and use that function to update the parent state value.
Like this:
class App extends Component {
constructor(){
super();
this.state={
renderOne: true,
}
this.update = this.update.bind(this);
}
update(){
this.setState({renderOne: false})
}
render() {
return (
<div className="App">
<BodyContent update={this.update}/>
{this.state.renderOne? <BottomOne /> : <BottomTwo/> }
</div>
);
}
}
Now inside BodyContent component call this.props.update() to render another component.
You can use state or props to render different components.
Example:
import React, {
Component
}
from 'react';
import BodyContent from './BodyContent';
import BottomOne from './BottomOne';
import BottomTwo from './BottomTwo';
class App extends Component {
constructor(props) {
super(props);
this.state = {
decider: false
};
}
render() {
const bottomContent = this.state.decider === true ? <BottomOne /> : <BottomTwo />;
return (
<div className="App">
<BodyContent />
{ bottomContent }
</div>
);
}
}
export
default App;
You can also directly use the components in the state and render them. Could be more flexible this way.
const BottomOne = () => <div>BottomOne</div>;
const BottomTwo = () => <div>BottomTwo</div>;
class Example extends React.Component {
constructor() {
super();
this.state = { show: BottomOne };
this.toggleComponent = this.toggleComponent.bind(this);
}
toggleComponent() {
// Use whatever logic here to decide.
let show = BottomOne;
if (this.state.show === BottomOne) {
show = BottomTwo;
}
this.setState({ show });
}
render() {
return (
<div>
<button onClick={this.toggleComponent}>Change</button>
<this.state.show />
</div>
);
}
}
ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>