Skip to content

Instantly share code, notes, and snippets.

@srele96
Created October 10, 2023 17:08
Show Gist options
  • Save srele96/8c6ec77f0aa4109bcee3b6f237d36f0d to your computer and use it in GitHub Desktop.
Save srele96/8c6ec77f0aa4109bcee3b6f237d36f0d to your computer and use it in GitHub Desktop.
how to use hook in class component in reactjs - https://codepen.io/Flexos96/pen/bGOzOxr?editors=1010
const { useState } = React;
// Which patterns do we use?
// React children can be utilized as a function, experiment with it
function F(props) {
console.log(props.children);
console.log(props.children(0));
console.log(props.children(0, 1));
console.log(props.children([]));
return props.children();
}
console.log(
<F>
{
/* function here, or react object, whatever... */
/* collect everything in parameter a using ... syntax */
(...a) => {
console.log(a);
return <div>{JSON.stringify(a)}</div>;
}
}
</F>
);
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// EXAMPLE --- BEGIN
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// Why is this useful?
// Imagine using hooks library such as react hook forms or
// some existing hooks API which we need to integrate with
// old components which have many lines of code, how do we use
// hooks in those components?
// One possible solution: Convert hooks to components.
function UseState(props) {
const [state, setState] = useState(props.initialState);
return props.children(state, setState);
}
class Foo extends React.Component {
render() {
return (
<div>
{/* For example, simple counter */}
<UseState initialState={0}>
{(state, setState) => {
return (
<button onClick={() => setState((p) => ++p)}>
{state} clicks
</button>
);
}}
</UseState>
{/* For example, or more complex object */}
<UseState initialState={{ foo: 0, bar: { a: [], b: "b" } }}>
{(state, setState) => {
return <div>{JSON.stringify(state)}</div>;
}}
</UseState>
</div>
);
}
}
function App() {
return (
<div>
<h1>How to use hooks in class components</h1>
<Foo />
</div>
);
}
ReactDOM.createRoot(document.querySelector("#root")).render(<App />);
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// EXAMPLE --- END
// -------------------------------------------------------------------
// -------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment