this is my first time to create a react application.
I wanted to pass buttons from index.js to table component that uses hooks.
Declaration:
const testButton = () => {
return (
<React.Fragment>
<button>Test1</button>
<button>Test2</button>
<button>Test3</button>
<button>Test4</button>
<button>Test5</button>
</React.Fragment>
);
};
pass it to Table component
return (
<React.Fragment>
<TestTable
{...{
testButton}} />
</React.Fragment>
Then, table component will use it to render the table, with the buttons included.
export default function TestTable({
testButton,
...props
})
return (
{testButton});
Am I doing it correctly?
How can I export this from index.js, import in Table component.js, and render in Table component?
Thank you.
I think what you want is:
const TestTable = ({ children }) => {
return (
<table>
<tr>
<td>Something...</td>
<td>{children}</td>
</tr>
</table>
)
}
And then:
const App = () => {
return (
<TestTable>
<button>Test 1</button>
<button>Test 2</button>
<button>Test 3</button>
</TestTable>
)
}
Hope it helps!
The React library promotes component composition. For a good recent writeup of this pattern read Robin Wieruchs article
You can refactor your TestTable component like the following:
Here I have added a codesandbox example: https://codesandbox.io/embed/smoosh-cache-ytfky
import React from 'react'
export default function TestTable(props) {
return (
<React.Fragment>
{props.children}
</React.Fragment>
)
}
Your TestButton component can remain mostly the same. You need to add the export keyword to the beginning of the component. Actually, the components are just plain old functions.
To learn more about the different styles of exporting functions see Alex Rauschmayer great description. there are arguments for using either default exports or named exports, I personally prefer named exports which is more declarative and just easier for me to see what is happening.
export default function TestButton() {
return (
<React.Fragment>
<button>Test1</button>
<button>Test2</button>
<button>Test3</button>
<button>Test4</button>
<button>Test5</button>
</React.Fragment>
);
};
You can now compose your two components in another function as follows:
export function DisplayTable(props) {
return (
<TestTable>
<TestButton />
</TestTable>
)
}
NOTE:
This assumes all your functions are in one file, but it is better to
put them in their own file and import / export them.
The this keyword is only applicable if you are writing a class component, if you write a function component then all you get is props, but you have to explicitly declare it in your function arguments.
I have converted all your ES6 arrow functions into regular javascript functions, I find it is easier to conceptualise, and learn these are just regular functions, but in React land they are your components.
As for React Hooks, they are a new introduction to React since 16.8 which really solve a specific use case of being able to handle state and side effects without using classes. see the original docs for a great description
In your index.js (where you return the buttons):
const TestButtons = () => (
<>
<button>Test1</button>
<button>Test2</button>
<button>Test3</button>
<button>Test4</button>
<button>Test5</button>
</>
)
export default TestButtons
Then, in your table.js:
import TestButtons from 'path/to/index.js'
const TestTable = () => (
<TestButtons />
)
You should use the import statement to import a component from another file.
Related
I've started seeing some of my team writing the following code which made me question if we're doing things the right way as I hadn't seen it written like this before.
import * as React from "react";
import "./styles.css";
function UsualExample() {
return <h1>This is the standard example…</h1>
}
export default function App() {
const CustomComponent = (): JSX.Element => <h1>But can I do this?</h1>
return (
<div className="App">
<UsualExample />
<CustomComponent />
</div>
);
}
It seems to render fine and I can't see any immediate adverse effects but is there some fundamental reason why we shouldn't be defining CustomComponent functional component from within another component?
CodeSandbox Example:
https://codesandbox.io/s/dreamy-mestorf-6lvtd?file=/src/App.tsx:0-342
This is not a good idea. Every time App rerenders it will make a brand new definition for CustomComponent. It has the same functionality, but since it's a different reference, react will need to unmount the old one and remount the new one. So you will be forcing react to do extra work on every render, and you'll also be resetting any state inside CustomComponent.
Instead, components should be declared on their own, not inside of rendering, so that they are created just once and then reused. If necessary, you can have the component accept props to customize its behavior:
const CustomComponent = (): JSX.Element => <h1>But can I do this?</h1>
export default function App() {
return (
<div className="App">
<UsualExample />
<CustomComponent />
</div>
);
}
On occasion, you may be doing something repetitive inside a single component and want to simplify the code by having a helper function. That's ok, but then you'll need to call it as a function, not render it as a component.
export default function App() {
const customCode = (): JSX.Element => <h1>But can I do this?</h1>
return (
<div className="App">
{customCode()}
<UsualExample />
{customCode()}
</div>
);
}
With this approach, react will be comparing an <h1> with an <h1>, and so it does not need to remount it.
It's not only a bad idea, it's a horrible idea. You haven't yet discovered composition (it's ok, it takes a while, you'll get there).
The only reason why you want to declare a component inside of another one is to close over a prop (maybe some state too, perhaps) that you want to capture in a child component - here's the trick - pass it as a prop to a new component and you can then declare the new component OUTSIDE.
Turn this:
function UsualExample() {
return <h1>This is the standard example…</h1>
}
export default function App({someProp}) {
// the only reason you're declaring it in here is because this component needs "something" that's available in <App/> - in this case, it's someProp
const CustomComponent = (): JSX.Element => <h1>I'm rendering {someProp}</h1>
return (
<div className="App">
<UsualExample />
<CustomComponent />
</div>
);
}
Into this:
function UsualExample() {
return <h1>This is the standard example…</h1>
}
const CustomComponent = ({someProp}) => <h1>I'm rendering {someProp}></h1>
export default function App({someProp}) {
return (
<div className="App">
<UsualExample />
{ /* but all you have to do is pass it as a prop and now you can declare your custom component outside */ }
<CustomComponent someProp={someProp} />
</div>
);
}
I have a component that uses two nested components that are based on render prop pattern. I need to combine props from both of them to be sent to the innermost function.
<Component1>
{(...props1) => (
<Component2>
{(...props2) => <MyComponent {...props1} {...props2} />}
</Component2>
)}
</Component1>
Now, I wanted to refactor the above inline functions into class functions, so as to avoid creating new functions on every render.
First attempt:
render() {
return <Component1>{this._render1}</Component1>;
}
_render1 = (...props1) => <Component2>{this._render2}</Component2>;
_render2 = (...props2) => <MyComponent {...props1} {...props2} />;
But now, in render2, I don't have access to props1, so I did:
render() {
return <Component1>{this._render1}</Component1>;
}
_render1 = (...props1) => <Component2>{this._render2(...props1)}</Component2>;
_render2 = (...props1) => (...props2) => <MyComponent {...props1} {...props2} />;
But here, I am back again to original problem of recreating inline functions on each render (inside _render2).
Please suggest a way to mitigate this problem. How can I best send the combined data down? What am I doing wrong here?
Did you got a chance to take a look on React.Context (https://reactjs.org/docs/context.html)?
You can create something like:
SomeContext.jsx
import React from "react";
export const SomeContext = React.createContext();
index.jsx
<SomeContext.Provider value={this.state.contextState}>
<div>
....
<Component2 />
<MyComponent />
...
</div>
</SomeContext.Provider>
Component2.jsx / MyComponent.jsx
import React from "react";
import { SomeContext } from "./SomeContext";
export default () => (
<SomeContext.Consumer>
your jsx with access to the props from parent.
</SomeContext.Consumer>
);
Hope it helps you.
I have written a Higher Order Component:
import React from 'react';
const NewHOC = (PassedComponent) => {
return class extends React.Component {
render(){
return (
<div>
<PassedComponent {...this.props}/>
</div>
)
}
}
}
export default NewHOC;
I am using the above in my App.js:
import React from 'react';
import Movie from './movie/Movie';
import MyHOC from './hoc/MyHOC';
import NewHOC from './hoc/NewHOC';
export default class App extends React.Component {
render() {
return (
<div>
Hello From React!!
<NewHOC>
<Movie name="Blade Runner"></Movie>
</NewHOC>
</div>
);
}
}
But, the warning I am getting is:
Warning: Functions are not valid as a React child. This may happen if
you return a Component instead of <Component /> from render. Or maybe
you meant to call this function rather than return it.
in NewHOC (created by App)
in div (created by App)
in App
The Movie.js file is:
import React from "react";
export default class Movie extends React.Component{
render() {
return <div>
Hello from Movie {this.props.name}
{this.props.children}</div>
}
}
What am I doing wrong?
I did encounter this error too because I didn't use the correct snytax at routing. This was in my App.js under the <Routes> section:
False:
<Route path="/movies/list" exact element={ MoviesList } />
Correct:
<Route path="/movies/list" exact element={ <MoviesList/> } />
So now the MoviesList is recognized as a component.
You are using it as a regular component, but it's actually a function that returns a component.
Try doing something like this:
const NewComponent = NewHOC(Movie)
And you will use it like this:
<NewComponent someProp="someValue" />
Here is a running example:
const NewHOC = (PassedComponent) => {
return class extends React.Component {
render() {
return (
<div>
<PassedComponent {...this.props} />
</div>
)
}
}
}
const Movie = ({name}) => <div>{name}</div>
const NewComponent = NewHOC(Movie);
function App() {
return (
<div>
<NewComponent name="Kill Bill" />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<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"/>
So basically NewHOC is just a function that accepts a component and returns a new component that renders the component passed in. We usually use this pattern to enhance components and share logic or data.
You can read about HOCS in the docs and I also recommend reading about the difference between react elements and components
I wrote an article about the different ways and patterns of sharing logic in react.
In my case i forgot to add the () after the function name inside the render function of a react component
public render() {
let ctrl = (
<>
<div className="aaa">
{this.renderView}
</div>
</>
);
return ctrl;
};
private renderView() : JSX.Element {
// some html
};
Changing the render method, as it states in the error message to
<div className="aaa">
{this.renderView()}
</div>
fixed the problem
I encountered this error while following the instructions here: https://reactjs.org/docs/add-react-to-a-website.html
Here is what I had:
ReactDOM.render(Header, headerContainer);
It should be:
ReactDOM.render(React.createElement(Header), headerContainer);
I had this error too. The problem was how to call the function.
Wrong Code:
const Component = () => {
const id = ({match}) => <h2>Test1: {match.params.id}</h2>
return <h1>{id}</h1>;
};
Whereas id is a function, So:
Correct code:
return <h1>{id()}</h1>;
Adding to sagiv's answer, we should create the parent component in such a way that it can consist all children components rather than returning the child components in the way you were trying to return.
Try to intentiate the parent component and pass the props inside it so that all children can use it like below
const NewComponent = NewHOC(Movie);
Here NewHOC is the parent component and all its child are going to use movie as props.
But any way, you guyd6 have solved a problem for new react developers as this might be a problem that can come too and here is where they can find the solution for that.
I was able to resolve this by using my calling my high order component before exporting the class component. My problem was specifically using react-i18next and its withTranslation method, but here was the solution:
export default withTranslation()(Header);
And then I was able to call the class Component as originally I had hoped:
<Header someProp={someValue} />
it also happens when you call a function from jsx directly rather than in an event. like
it will show the error if you write like
<h1>{this.myFunc}<h2>
it will go if you write:
<h1 onClick={this.myFunc}>Hit Me</h1>
I was getting this from webpack lazy loading like this
import Loader from 'some-loader-component';
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
fallback: Loader, // warning
});
render() {
return <WishlistPageComponent />;
}
// changed to this then it's suddenly fine
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
fallback: '', // all good
});
In my case, I was transport class component from parent and use it inside as a prop var, using typescript and Formik, and run well like this:
Parent 1
import Parent2 from './../components/Parent2/parent2'
import Parent3 from './../components/Parent3/parent3'
export default class Parent1 extends React.Component {
render(){
<React.Fragment>
<Parent2 componentToFormik={Parent3} />
</React.Fragment>
}
}
Parent 2
export default class Parent2 extends React.Component{
render(){
const { componentToFormik } = this.props
return(
<Formik
render={(formikProps) => {
return(
<React.fragment>
{(new componentToFormik(formikProps)).render()}
</React.fragment>
)
}}
/>
)
}
}
What would be wrong with doing;
<div className="" key={index}>
{i.title}
</div>
[/*Use IIFE */]
{(function () {
if (child.children && child.children.length !== 0) {
let menu = createMenu(child.children);
console.log("nested menu", menu);
return menu;
}
})()}
In my case I forgot to remove this part '() =>'. Stupid ctrl+c+v mistake.
const Account = () => ({ name }) => {
So it should be like this:
const Account = ({ name }) => {
In my case
<Link key={uuid()} to="#" className="tag">
{post.department_name.toString}
</Link>
changed with
<Link key={uuid()} to="#" className="tag">
{post.department_name.toString()}
</Link>
You should use
const FunctionName = function (){
return (
`<div>
hello world
<div/>
`
)
};
if you use Es6 shorthand function it will give error use regular old javascript function.
Can someone please explain Higher-order components in React. I have read and re-read the documentation but cannot seem to get a better understanding. According to the documentation, HOCs help remove duplication by creating a primary function that returns a react component, by passing arguments to that function.
I have a few questions on that.
If HOCs create a new enhanced component, can it be possible not to pass in any component as argument at all?
In an example such as this, which is the higher order component, the Button or the EnhancedButton.
I tried creating one HOC like this:
// createSetup.js
import React from 'react';
export default function createSetup(options) {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.testFunction = this.testFunction.bind(this);
}
testFunction() {
console.log("This is a test function");
}
render() {
return <p>{options.name}</p>
}
}
}
// main.js
import React from 'react';
import {render} from 'react-dom';
import createSetup from './createSetup';
render((<div>{() => createSetup({name: 'name'})}</div>),
document.getElementById('root'););
Running this does not show the HOC, only the div
Can anyone help out with a better example than the ones given?
A HOC is a function that takes a Component as one of its parameters and enhances that component in some way.
If HOCs create a new enhanced component, can it be possible not to pass in any component as argument at all?
Nope, then it wouldn't be a HOC, because one of the conditions is that they take a component as one of the arguments and they return a new Component that has some added functionality.
In an example such as this, which is the higher order component, the Button or the EnhancedButton.
EnhanceButton is the HOC and FinalButton is the enhanced component.
I tried creating one HOC like this: ... Running this does not show the HOC, only the div
That's because your createSetup function is not a HOC... It's a function that returns a component, yes, but it does not take a component as an argument in order to enhance it.
Let's see an example of a basic HOC:
const renderWhen = (condition, Component) =>
props => condition(props)
? <Component {...props} />
: null
);
And you could use it like this:
const EnhancedLink = renderWhen(({invisible}) => !invisible, 'a');
Now your EnhancedLink will be like a a component but if you pass the property invisible set to true it won't render... So we have enhanced the default behaviour of the a component and you could do that with any other component.
In many cases HOC functions are curried and the Component arg goes last... Like this:
const renderWhen = condition => Component =>
props => condition(props)
? <Component {...props} />
: null
);
Like the connect function of react-redux... That makes composition easier. Have a look at recompose.
In short, If you assume functions are analogues to Components, Closure is analogous to HOC.
Try your createSetup.js with:
const createSetup = options => <p>{options.name}</p>;
and your main.js
const comp = createSetup({ name: 'name' });
render((<div>{comp}</div>),
document.getElementById('root'));
A higher-order component (HOC) is an advanced technique in React for reusing component logic. Concretely, a higher-order component is a function that takes a component and returns a new component.
A HOC is a pure function with zero side-effects.
Example: CONDITIONALLY RENDER COMPONENTS
Suppose we have a component that needs to be rendered only when a user is authenticated — it is a protected component. We can create a HOC named WithAuth() to wrap that protected component, and then do a check in the HOC that will render only that particular component if the user has been authenticated.
A basic withAuth() HOC, according to the example above, can be written as follows:
// withAuth.js
import React from "react";
export function withAuth(Component) {
return class AuthenticatedComponent extends React.Component {
isAuthenticated() {
return this.props.isAuthenticated;
}
/**
* Render
*/
render() {
const loginErrorMessage = (
<div>
Please login in order to view this part of the application.
</div>
);
return (
<div>
{ this.isAuthenticated === true ? <Component {...this.props} /> : loginErrorMessage }
</div>
);
}
};
}
export default withAuth;
The code above is a HOC named withAuth. It basically takes a component and returns a new component, named AuthenticatedComponent, that checks whether the user is authenticated. If the user is not authenticated, it returns the loginErrorMessage component; if the user is authenticated, it returns the wrapped component.
Note: this.props.isAuthenticated has to be set from your application’s
logic. (Or else use react-redux to retrieve it from the global state.)
To make use of our HOC in a protected component, we’d use it like so:
// MyProtectedComponent.js
import React from "react";
import {withAuth} from "./withAuth.js";
export class MyProectedComponent extends React.Component {
/**
* Render
*/
render() {
return (
<div>
This is only viewable by authenticated users.
</div>
);
}
}
// Now wrap MyPrivateComponent with the requireAuthentication function
export default withAuth(MyPrivateComponent);
Here, we create a component that is viewable only by users who are authenticated. We wrap that component in our withAuth HOC to protect the component from users who are not authenticated.
Source
// HIGHER ORDER COMPOENTS IN REACT
// Higher order components are JavaScript functions used for adding
// additional functionalities to the existing component.
// file 1: hoc.js (will write our higher order component logic) -- code start -->
const messageCheckHOC = (OriginalComponent) => {
// OriginalComponent is component passed to HOC
const NewComponent = (props) => {
// business logic of HOC
if (!props.isAllowedToView) {
return <b> Not Allowed To View The MSG </b>;
}
// here we can pass the props to component
return <OriginalComponent {...props} />;
};
// returning new Component with updated Props and UI
return NewComponent;
};
export default messageCheckHOC;
// file 1: hoc.js -- code end -->
// file 2: message.js -- code start -->
// this is the basic component we are wrapping with HOC
// to check the permission isAllowedToView msg if not display fallback UI
import messageCheckHOC from "./hoc";
const MSG = ({ name, msg }) => {
return (
<h3>
{name} - {msg}
</h3>
);
};
export default messageCheckHOC(MSG);
// file 2: message.js -- code end -->
// file 3 : App.js -- code start --->
import MSG from "./message.js";
export default function App() {
return (
<div className="App">
<h3>HOC COMPONENTS </h3>
<MSG name="Mac" msg="Heyy !!! " isAllowedToView={true} />
<MSG name="Robin" msg="Hello ! " isAllowedToView={true} />
<MSG name="Eyann" msg="How are you" isAllowedToView={false} />
</div>
);
}
// file 3 : App.js -- code end --->
I read an article and the author critic below code, I wonder what's wrong with it. I was starting to learn React, too bad the author did not point out what's his problem with the code below. I tested the code below, it's running fine.
import React from 'react';
import './App.css';
const TodoItems = React.createClass({
getInitialState() {
return {
items : [
{id:1,name:"Gym"},
{id:2,name:"Jump"},
{id:3,name:"Racing"}
]
}
},
renderItem(){
return(
<ul>
{this.state.items.map((item,i) =>
<li key={i}>item.name</li>
)}
</ul>
)
},
render(){
return (
<renderItem />
)
}
})
ReactDOM.render(<TodoItems />,document.getElementById('app'));
The method renderItem should be outside as a functional or stateless component:
const RenderItem = (props) => {
return(
<ul>
{props.items.map((item,i) =>
<li key={i}>item.name</li>
)}
</ul>
)
};
The render method of the parent component should be:
render(){
return (
<RenderItem items={this.state.items} />
)
}
This is the standard way that we write React components. It causes maintainability issues when you write it that way.
In short, you code will not ensure component re-usability.
With React, you'll get the most of re-usability. In the above code, I can see that you are trying to render the items in the state in the function renderItem(). The need of using functions in any language is also to ensure re-usability. So, in React when you when you want to re-use a part which will return a HTML elements, make it as a separate component.
See the following fiddle
https://jsfiddle.net/Pranesh456/b6v6fxrj/1/
Here, I made the renderItem() as a separate component <RenderItem> which can be reused in n number of other components..