Here is the example code:
import React, { useContext } from 'react';
import { Context } from './MainContext';
import ReactDomServer from 'react-dom/server';
//Import SomeOtherComponent
import { SomeOtherComponent} from './SomeOtherComponent';
export const SomeComponent = () => {
const { state } = useContext(Context);
const result = ReactDomServer.renderToStaticMarkup(
<SomeOtherComponent
name={state.name}
date={state.date}
/>
);
SomeComponent will be used in a handleSubmit function like so:
const handleSubmit = (e) => {
e.preventDefault();
SomeComponent({ ...state });
setState((state) => ({
...state,
submitted: true,
}));
};
I am getting the following error:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app See fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
I believe the issue is that I'm calling useContext and not returning anything. - How can this function be restructured to account for the issue and maintain usage of ReactDomServer.renderToStaticMarkup
on an imported component?
I ended up figuring out the issue.
I was already passing state as an argument in SomeComponent
within my handleSubmit
function, so the best solution for me was to forego the useContext
hook entirely and simply let SomeComponent
accept state as an argument.
Solution:
import React from 'react';
import ReactDomServer from 'react-dom/server';
//Import SomeOtherComponent
import { SomeOtherComponent} from './SomeOtherComponent';
export const SomeComponent = ({...state}) => {
const result = ReactDomServer.renderToStaticMarkup(
<SomeOtherComponent
name={state.name}
date={state.date}
/>
);