React call functions on renderless component - javascript

I need to have a component for handling settings, this component (called Settings) stores state using useState(), for example the primary color.
I need to create a single instance of this component and make it available to every component in the app. Luckily, I already pass down a state dict to every component (I'm very unsure if this is the correct way to achieve that btw), so I can just include this Settings constant.
My problem is that I don't know how to create the component for this purpose, so that I can call its functions and pass it to children.
Here is roughly what my Settings component looks like:
const Settings = (props) => {
const [primaryColor, setPrimaryColor] = useState("")
const getColorTheme = (): string => {
return primaryColor
}
const setColorTheme = (color: string): void => {
setPrimaryColor(color)
}
return null
}
export default Settings
Then I would like to be able to do something like this somewhere else in the app:
const App = () => {
const settings = <Settings />
return (
<div style={{ color: settings.getColorTheme() }}></div>
)
}
Bear in mind that I'm completely new to react, so my approach is probably completely wrong.

You can use a custom Higher Order Component(HOC) for this purpose, which is easier than creating a context(even thougn context is also a HOC). A HOC takes a component and returns a new component. You can send any data from your HOC to the received component.
const withSettings = (Component) => {
const [settings, setSettings] = useState({})
// ...
// ...
<Component {...props} settings={settings}/>
);
And you can use it like this:
const Component = ({ settings }) => {
...your settings UI
}
export default SettingsUI = withSettings(Component);
You can read more about HOCs in the official react documentation

Related

React HOC: Pass data attributes to the first child/element of wrapped component

I have a hoc component like this:
export const withAttrs = (WrappedComponent) => {
const ModifiedComponent = (props) => (
<WrappedComponent {...props} data-test-id="this-is-a-element" />
);
return ModifiedComponent;
};
export default withAttrs;
and I use it like this:
import React from 'react';
import withAttrs from './withAttrs';
const SomeLink = () => <a><p>hey</p</a>;
export default withAttrs(SomeLink);
I expect to have an anchor tag like this:
<a data-test-id="this-is-a-element"><p>hey</p></a>
But the hoc doesn't add the data-attribute to the first element. Is there a way to achieve this?
But the hoc doesn't add the data-attribute to the first element.
It's not the HOC that isn't adding it, it's SomeLink, which doesn't do anything with the props the HOC passes to it.
The simple answer is to update SomeLink:
const SomeLink = (props) => <a {...props}><p>hey</p></a>;
That's by far the better thing to do than the following.
If you can't do that, you could make your HOC add the property after the fact, but it seems inappropriate to have the HOC reach inside the component and change things. In fact, React makes the element objects it creates immutable, which strongly suggests you shouldn't try to mess with them.
Still, it's possible, it's probably just a bad idea:
export const withAttrs = (WrappedComponent) => {
const ModifiedComponent = (props) => {
// Note we're *calling* the function, not just putting it in
// a React element via JSX; we're using it as a subroutine of
// this component rather than as its own component.
// This will only work with function components. (You could
// write a version that handles class components as well,
// but offhand I don't think you can make one HOC that handles
// both in this case.)
const result = WrappedComponent(props);
return {
...result,
props: {
...result.props,
"data-test-id": "this-is-a-element",
},
};
};
return ModifiedComponent;
};
/*export*/ const withAttrs = (WrappedComponent) => {
const ModifiedComponent = (props) => {
// Note we're *calling* the function, not just putting it in
// a React element via JSX; we're using it as a subroutine of
// this component rather than as its own component.
// This will only work with function components. (You could
// write a version that handles class components as well,
// but offhand I don't think you can make one HOC that handles
// both in this case.)
const result = WrappedComponent(props);
// THIS IS PROBABLY A VERY BAD IDEA. React makes these objects
// immutable, probably for a reason. We shouldn't be mucking
// with them.
return {
...result,
props: {
...result.props,
"data-test-id": "this-is-a-element",
},
};
};
return ModifiedComponent;
};
const SomeLink = () => <a><p>hey</p></a>;
const SomeLinkWrapped = withAttrs(SomeLink);
const Example = () => {
return <div>
<div>Unwrapped:</div>
<SomeLink />
<div>Wrapped:</div>
<SomeLinkWrapped />
</div>;
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Example />);
/* So we can see that it was applied */
[data-test-id=this-is-a-element] {
color: green;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
Again, I don't think I'd do that except as a very last resort, and I wouldn't be surprised if it breaks in future versions of React.

Convert class component to functional components using hooks

I am trying to convert this class component to functional component using hooks
import React, { Component, cloneElement } from 'react';
class Dialog extends Component {
constructor(props) {
super(props);
this.id = uuid();
}
render(){
return ( <div>Hello Dialog</div> );
}
}
This component is initiated with a specific ID because I may have to use multiple instances of them. How can I achieve this if I use functional component?
One solution would be to use useEffect to create your ID at the first render, and store it in the state :
const Dialog = () => {
const [id, setId] = useState(null);
useEffect(() => {
setId(uuid())
}, [])
return <div>Hello Dialog</div>
}
Giving an empty array as the second parameter of useEffect makes it unable to trigger more than once.
But another extremely simple solution could be to just... create it outside of your component :
const id = uuid();
const Dialog = () => {
return <div>Hello Dialog</div>
}
You may store it in state:
const [id] = useState(uuid()); // uuid will be called in every render but only the first one will be used for initiation
// or using lazy initial state
const [id] = useState(() => uuid()); // uuid will only be called once for initiation
You may also store it in React ref:
const id = useRef(null);
if(!id.current) {
// initialise
id.current = uuid();
}
// To access it’s value
console.log(id.current);
Any instance property becomes a ref pretty much, and you would access idRef.current in this case for the id
function Dialog() {
const idRef = useRef(uuid())
return <div>Hello Dialog</div>
}
Thank you all, your solutions works well. I also try this solution and I find it OK too: replace this.id with Dialog.id. Is there any downside with this solution?

Using a global object in React Context that is not related to state

I want to have a global object that is available to my app where I can retrieve the value anywhere and also set a new value anywhere. Currently I have only used Context for values that are related to state i.e something needs to render again when the value changes. For example:
import React from 'react';
const TokenContext = React.createContext({
token: null,
setToken: () => {}
});
export default TokenContext;
import React, { useState } from 'react';
import './App.css';
import Title from './Title';
import TokenContext from './TokenContext';
function App() {
const [token, setToken] = useState(null);
return(
<TokenContext.Provider value={{ token, setToken }}>
<Title />
</TokenContext.Provider>
);
}
export default App;
How would I approach this if I just want to store a JS object in context (not a state) and also change the value anywhere?
The global context concept in React world was born to resolve problem with passing down props via multiple component layer. And when working with React, we want to re-render whenever "data source" changes. One way data binding in React makes this flow easier to code, debug and maintain as well.
So what is your specific purpose of store a global object and for nothing happen when that object got changes? If nothing re-render whenever it changes, so what is the main use of it?
Prevent re-render in React has multiple ways like useEffect or old shouldComponentUpdate method. I think they can help if your main idea is just prevent re-render in some very specific cases.
Use it as state management libraries like Redux.
You have a global object (store) and you query the value through context, but you also need to add forceUpdate() because mutating the object won't trigger a render as its not part of React API:
const globalObject = { counter: 0 };
const Context = React.createContext(globalObject);
const Consumer = () => {
const [, render] = useReducer(p => !p, false);
const store = useContext(Context);
const onClick = () => {
store.counter = store.counter + 1;
render();
};
return (
<>
<button onClick={onClick}>Render</button>
<div>{globalObject.counter}</div>
</>
);
};
const App = () => {
return (
<Context.Provider value={globalObject}>
<Consumer />
</Context.Provider>
);
};

react keep data in sync

I have a real-time filter structure on a page. The data from my inputs are kept in my State but also as a URL query so that when someone opens the page with filters in the URL the right filters are already selected.
I'm struggling to find a stable way to keep these 2 in sync. Currently, I'm getting the data from my URL on load and setting the data in my URL whenever I change my state, but this structure makes it virtually impossible to reuse the components involved and mistakes can easily lead to infinite loops, it's also virtually impossible to expand. Is there a better architecture to handle keeping these in sync?
I would recommend managing the state of the filters in the view from query params. If you use react-router, you can use query params instead of state and in the render method get params need for view elements. After change filters you need implement redirect. For more convenience it may be better to use qs module. With this approach you will also receive a ready-made parameter for request to backend.
Example container:
const initRequestFields = {someFilterByDefault: ''};
class Example extends Component{
constructor(props) {
super(props);
this.lastSearch = '';
}
componentDidMount() {
this.checkQuery();
}
componentDidUpdate() {
this.checkQuery();
}
checkQuery() {
const {location: {search}, history} = this.props;
if (search) {
this.getData();
} else {
history.replace({path: '/some-route', search: qs.stringify(initRequestFields)});
}
}
getData() {
const {actionGetData, location: {search}} = this.props;
const queryString = search || `?${qs.stringify(initRequestFields)}`;
if (this.lastSearch !== queryString) {
this.lastSearch = queryString;
actionGetData(queryString);
}
}
onChangeFilters = (values) => {
const {history} = this.props;
history.push({path: '/some-route', search: qs.stringify(values)});
};
render() {
const {location: {search}} = this.props;
render(<Filters values={qs.parse(search)} onChangeFilers={this.onChangeFilters} />)
}
}
This logic is best kept in the highest container passing the values to the components.
For get more info:
Query parameters in react router
Qs module for ease work with query
If you worry about bundle size with qs module
This answer used React Hooks
You want to keep the URL with the state, you need a two way sync, from the URL to the state (when the component mount) and from the state to the URL (when you updating the filter).
With the React Router Hooks, you can get a reactive object with the URL, and use it as the state, this is one way- from URL to the component.
The reverse way- update the URL when the component changed, can be done with history.replace.
You can hide this two way in a custom hook, and it will work like the regular useState hook:
To use Query Params as state:
import { useHistory, useLocation} from 'react-router-dom'
const useQueryAsState = () => {
const { pathname, search } = useLocation()
const history = useHistory()
// helper method to create an object from URLSearchParams
const params = getQueryParamsAsObject(search)
const updateQuery = (updatedParams) => {
Object.assign(params, updatedParams)
// helper method to convert {key1:value,k:v} to '?key1=value&k=v'
history.replace(pathname + objectToQueryParams(params))
}
return [params, updateQuery]
}
To use Route Params as state:
import { generatePath, useHistory, useRouteMatch } from 'react-router-dom'
const useParamsAsState = () => {
const { path, params } = useRouteMatch()
const history = useHistory()
const updateParams = (updatedParams) => {
Object.assign(params, updatedParams)
history.push(generatePath(path, params))
}
return [params, updateParams]
}
Note to the history.replace in the Query Params code and to the history.push in the Route Params code.
Usage: (Not a real component from my code, sorry if there are compilation issues)
const ExampleComponent = () => {
const [{ user }, updateParams] = useParamsAsState()
const [{ showDetails }, updateQuery] = useQueryAsState()
return <div>
{user}<br/ >{showDetails === 'true' && 'Some details'}
<DropDown ... onSelect={(selected) => updateParams({ user: selected }) />
<Checkbox ... onChange={(isChecked) => updateQuery({ showDetails: isChecked} })} />
</div>
}
I published this custom hook as npm package: use-route-as-state

Unit testing connected higher-order components in React/Enzyme

In normal connected React components, in order to make unit testing easier, I've seen the pattern of exporting the base component, while export defaulting the connected component. It works well for simple tests that handle the actual functionality of the component without getting cluttered with redux stores and router mocking.
I'm looking for an analog for higher-order components. For instance, given a trivial higher-order component:
export default function exampleHoc(Wrapped) {
const ExampleHoc = props => (
<Wrapped {...props.reduxStore} hoc={true} />
);
return connect(
state => ({
reduxStore: state.example.reduxStore,
}))(ExampleHoc);
}
I'd like to verify that props.hoc === true in a unit test, without having to wire up the other higher-order components that <ExampleHoc> strings along.
My best design is passing along a flag:
export default function exampleHoc(Wrapped, exportUnconnectedForTest) {
const ExampleHoc = props => (
<Wrapped {...props.reduxStore} hoc={true} />
);
if (exportUnconnectedForTest) {
return ExampleHoc;
}
return connect(
state => ({
reduxStore: state.example.reduxStore,
}))(ExampleHoc);
}
This makes it easy to test
const DummyComponent = () => <div />;
const Sut = exampleHoc(DummyComponent, true);
...
test('props value should be passed', () => {
const sut = shallow(<Sut />);
const childProps = sut.find(DummyComponent).props();
expect(sut.childProps.hoc).to.equal(true);
});
while still happily passing along the wrapped output to any regular callers of the method.
It works, but it seems clunky to me. Is there a better/established pattern for delivering the unwrapped interior of a higher-order component?

Categories

Resources