Converting a class-based component to Functional Component
class TableRowWrapper extends Component {
render() {
return <tr>{this.props.children}</tr>;
}
}
Now the functional version of the above component
const TableRowWrapper = ({ children }) => {
<tr>{children}</tr>;
};
Explanation of the syntax – Why have I wrapped the ‘children’ in curly braces.
This is called a “destructuring”. Actually, I am passing an object as an argument to the function, but the destructuring uses only the named properties of the object. Simple example below.
const destructuring = ({ used }) => console.log(used);
const properties = {
unused: 1,
used: 2
};
destructuring(properties); // 2
Passing down props to functional components
You would need to pass down each prop individually for each function that you needed to call. In below case ChildFunctionalComp is the Child component.
<ChildFunctionalComp
onFirstNameChange={this.firstNameChange}
onHide={close}
show={this.state.showModal}
/>
And then in the CreateProfile component you can either do
const ChildFunctionalComp = ({onFirstNameChange, onHide, show }) => {...}
with destructuring it will assign the matching property names/values to the passed in variables. The names just have to match with the properties
or just do
const ChildFunctionalComp = (props) => {...}
and in each place call props.onHide
or whatever prop you are trying to access.
Syntax for declaring, exporting and importing of pure functional component.
1-st Option
import React, { Component } from "react";
import { Route, Redirect } from "react-router-dom";
const ProtectedRoutes = ({ component: Component, authenticated, ...rest }) => {
return (
<Route
{...rest}
render={props =>
authenticated === true ? (
<Component {...props} {...rest} />
) : (
<Redirect
to={{
pathname: "/api/auth/login",
state: { from: props.location }
}}
/>
)
}
/>
);
};
export default ProtectedRoutes;
Then importing it to another component like below
import ProtectedRoutes from "./ProtectedRoutes";
2-nd Option
import React, { Component } from "react";
import { Route, Redirect } from "react-router-dom";
const ProtectedRoutes = ({ component: Component, authenticated, ...rest }) => {
return (
<Route
{...rest}
render={props =>
authenticated === true ? (
<Component {...props} {...rest} />
) : (
<Redirect
to={{
pathname: "/api/auth/login",
state: { from: props.location }
}}
/>
)
}
/>
);
};
Then importing it to another component like below
import { ProtectedRoutes } from "./ProtectedRoutes";
ES6 doesn’t allow export default const. You must declare the constant first then export it:
const Header = () => {
return <pre>Header</pre>;
};
export default Header;
This constraint exists to avoid writting export default a, b, c; that is forbidden: only one variable can be exported as default