Ad

How To Pass Default State For React Global Store Provider From Laravel Blade?

I have set up a global storage for my App, using React Context API like this:

class App extends Component {
   render() {
      return (
        <SettingsProvider>
            <Items />
        </SettingsProvider>
      );
   }
}

render(<App />, document.getElementById('app'));

And mu provider looks something like this:

const defaultState = {test:'test'}

function SettingsProvider({children}) {
    const [state, dispatch] = React.useReducer(settingsReducer, defaultState);

    return (
        <SettingsContext.Provider value={{ state, dispatch }}>
            {children}
        </SettingsContext.Provider>
    )
}

Everything is working as expected. But now I would like to pass defaultState to SettingsProvider from Laravel rather than defining it in my javascript, using something like this:

<div id="app" defaultstate="{{$state}}"></div>

But I haven't figured out, how to access those values from my SettingsProvider... How could I implement this?

Ad

Answer

React doesn't know about HTML attributes. You need to pass the defaultState attribute in your Blade template as props to your App component then pass down the prop to SettingsProvider component.

App.jsx

class App extends Component {
   render() {
      return (
        <SettingsProvider defaultState={this.props.defaultState}>
            <Items />
        </SettingsProvider>
      );
   }
}

if (document.getElementById('app')) {
    // find element by id
    const element = document.getElementById('app')

    // Get element's defaultState attribute
    const defaultState = element.getAttribute('defaultState')

    // render element
    render(<App defaultState={defaultState} />, element);
}

SettingsProvider.jsx

const initialState = {test:'test'}

function SettingsProvider({children, defaultState}) {
    const [state, dispatch] = React.useReducer(
        settingsReducer,
        //This will override initialState entries with the values you passed via Blade
        {
            ...initialState,
            ...defaultState
        }
    );

    return (
        <SettingsContext.Provider value={{ state, dispatch }}>
            {children}
        </SettingsContext.Provider>
    )
}
Ad
source: stackoverflow.com
Ad