Showing posts with label React. Show all posts
Showing posts with label React. Show all posts

Friday, 14 July 2023

Solution Error : validateDOMNesting body cannot appear as a child of

 Today I will try to share how to solving and solution error "validateDOMNesting body cannot appear as a child of ",  There are so many things that cause this problem,  but for my situation, I can solve this problem like example scripts below :

                <body>

                {/*<!-- ======= Header ======= -->*/}
                <header id="header" className="fixed-top ">
                    <div className="container d-flex align-items-center">
                    </div>
                </header>
                </body>

The script above sometimes resulting the error "validateDOMNesting body".

To solve this error, just remove tag <body> </body> in JSX,  like the script below :

                 <header id="header" className="fixed-top ">
                    <div className="container d-flex align-items-center">
                    </div>
                </header> 


That is just a little information and hope can be helping you. Thanks

Wednesday, 5 July 2023

redirect in react had been deprecated for new version solution

Redirect and Navigate Component

The Redirect component was usually used in previous versions of the react-router-dom package to quickly do redirects by simply importing the component from react-router-dom and then making use of the component by providing the to prop, passing the page you desire to redirect to.

import { Redirect } from 'react-router-dom';

<Route path='/redirect-page' element={ <Redirect to="/error-page" /> }/>


With the release of React Router v6, the Redirect component was removed and replaced with the Navigate component, which operates just as the Redirect component does by taking in the to prop to enable you to redirect to the page you specify.

Following example scripts of solution with Navigate scripts :

import { Navigate } from 'react-router-dom';

<Route path="/redirect" element={ <Navigate to="/error-page" /> } />

another sample :

return(<Navigate to="/dashboard" />)


Source : https://stackabuse.com/redirects-in-react-router/


 

Saturday, 24 June 2023

How to show script from variable or function with html scripts value result into JSX React

 Today I will try to share information or tutorial about "How to show script from variable or function  with html scripts value result into JSX React ". This tutorial may be rare and short, but hope this information can help you. Okay lets see piece of code below :

This is a source code function that return html value 

export const getUiTableStatus = (val) =>{
    let retVal = '';
    if(val === '0'){
        retVal = `<span class="badge bg-danger">Start</span>`;
    }else if(val === '1'){
        retVal = `<span class="badge bg-warning">On Progress</span>`;
    }else{
        retVal = `<span class="badge bg-success">Done</span>`;
    }

    return retVal;
}


We will try to render the value of the above function into JSX react 

<div dangerouslySetInnerHTML={{__html: getUiTableStatus(result.status)}}>

The output of this poject like below :








Hope this information can help you. Any questions please leave comments below. Thanks
 


Friday, 16 June 2023

How to submit form without refreshing page in react

 If you work with react and sometimes you want your web to do not refreshing the page when you click button submit. The solution of this problem are just try this scripts below (for example) :

const handleSubmit = event => {
    console.log('handleSubmit ran');
    event.preventDefault(); // 👈️ prevent page refresh

    // 👇️ access input values here
    console.log('firstName 👉️', firstName);
    console.log('lastName 👉️', lastName);

    // 👇️ clear all input values in the form
    setFirstName('');
    setLastName('');
  };

That is solution " submit form without refreshing page in react". Hope this example can helping you.


Source :https://bobbyhadz.com/blog/react-prevent-page-refresh-on-form-submit#:~:text=Use%20the%20preventDefault()%20method,is%20to%20refresh%20the%20page.





Sunday, 11 June 2023

Calling external function in react JSX

 If you want to call function from another file.js in jsx you can use script like below :

window.function()

Thursday, 8 June 2023

Sunday, 4 June 2023

Context Basic for Routing Protection in React

Among the changes in React 16.3 is a new stable version of the Context API. We’re going to take a look at how it works by building a protected route component.

What is Context?

Context is about encapsulating state. It allows us to pass data from a parent provider component to any subscribed component down the tree. Without state management we often have to “drill” props through every component along the way.

Isn’t that what Redux is for?

Yes, Context operates similarly to how components can connect to Redux’s global state. However, a native element like Context will often be a better solution for small to medium apps that don’t need the complex overhead of Redux.

Basic Concepts

There are three elements to Context:

  • createContext — Calling this returns a pair of components, Provider and Consumer.
  • Provider — a Component that allows for one or more Consumers to subscribe to changes.
  • Consumer —a Component subscribed to a Provider

Let’s Start Building

We’re going to build an app with two routes. One is a landing page with global access. The other is a dashboard page with restricted access for logged in users. You can find the final version here.

Try it out: go to /dashboard while logged out. Log in and navigate freely between routes. From the dashboard, log out and it’ll kick you out to the landing page.

Context Header

To demonstrate Context’s basic functionality, let’s start by building a header component that lets us log in and out. First, create our context in a new file.

/* AuthContext.js */import React from 'react';const AuthContext = React.createContext();

Export a component AuthProvider to define our state (whether the user is logged in) and pass its state to the value prop on the Provider. We’ll simply expose AuthConsumer with a meaningful name.

/* AuthContext.js */...class AuthProvider extends React.Component {
state = { isAuth: false }
render() {
return (
<AuthContext.Provider
value={{ isAuth: this.state.isAuth }}
>
{this.props.children}
</AuthContext.Provider>
)
}
}
const AuthConsumer = AuthContext.Consumerexport { AuthProvider, AuthConsumer }

In index.js, wrap our app in AuthProvider.

/* index.js */
import React from 'react';
import { render } from 'react-dom';
import { AuthProvider } from './AuthContext';
import Header from './Header';
const App = () => (
<div>
<AuthProvider>
<Header />
</AuthProvider>
</div>
);
render(<App />, document.getElementById('root'));

Now create our Header and import our AuthConsumer (I’m leaving styling out for clarity).

/* Header.js */
import React from 'react'
import { AuthConsumer } from './AuthContext'
import { Link } from 'react-router-dom'
export default () => (
<header>
<AuthConsumer>

</AuthConsumer>
</header>
)

Context Consumers must have a function as their direct child. This will be passed the value from our Provider.

/* Header.js */
...
export default () => (
<header>
<AuthConsumer>
{({ isAuth }) => (
<div>
<h3>
<Link to="/">
HOME
</Link>
</h3>
{isAuth ? (
<ul>
<Link to="/dashboard">
Dashboard
</Link>
<button>
logout
</button>
</ul>
) : (
<button>login</button>
)}
</div>
)}
</AuthConsumer>
</header>
)

Because isAuth is set to false, only the login button will be visible. Try changing the value to true (it’ll switch to the logout button).

Ok, let’s try switching isAuth in code. We’ll pass a login and logout function from our Provider.

/* AuthContext.js */
...
class AuthProvider extends React.Component {
state = { isAuth: false }
constructor() {
super()
this.login = this.login.bind(this)
this.logout = this.logout.bind(this)
}
login() {
// setting timeout to mimic an async login
setTimeout(() => this.setState({ isAuth: true }), 1000)
}
logout() {
this.setState({ isAuth: false })
}
render() {
return (
<AuthContext.Provider
value={{
isAuth: this.state.isAuth,
login: this.login,
logout: this.logout

}}
>
{this.props.children}
</AuthContext.Provider>
)
}
}

These functions will allow us to toggle our auth state in Header.

/* Header.js */
...
export default () => (
<header>
<AuthConsumer>
{({ isAuth, login, logout }) => (
<div>
<h3>
<Link to="/">
HOME
</Link>
</h3>
{isAuth ? (
<ul>
<Link to="/dashboard">
Dashboard
</Link>
<button onClick={logout}>
logout
</button>
</ul>
) : (
<button onClick={login}>login</button>
)}
</div>
)}
</AuthConsumer>
</header>
)

Protected Route With Context

Now that we have covered the basics, let’s extend what we’ve learned to create a protected route component.

First make Landing and Dashboard page components. Our dashboard will only be visible when the user is logged in. Both pages will be as simple, as below:

/* Dashboard.js */
import React from 'react'
const Dashboard = () => <h2>User Dashboard</h2>export default Dashboard

Now let’s route to these pages.

/* index.js */
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { AuthProvider } from './AuthContext';
import Landing from './Landing';
import Dashboard from './Dashboard';

import Header from './Header';
const App = () => (
<div>
<Router>
<AuthProvider>
<Header />
<Switch>
<Route path="/dashboard" component={Dashboard} />
<Route path="/" component={Landing} />
</Switch>

</AuthProvider>
</Router>
</div>
);
render(<App />, document.getElementById('root'));

In this current state you can navigate to both / and /dashboard. We’ll make a special route component that checks if a user is logged in called ProtectedRoute. The set up is similar to our Header component.

/* ProtectedRoute.js */
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { AuthConsumer } from './AuthContext';
const ProtectedRoute = () => (
<AuthConsumer>
{({ isAuth }) => (
)}
</AuthConsumer>
);
export default ProtectedRoute;

The private route will function just like a regular react-router route, so we’ll expose the component and any other props passed to it.

const ProtectedRoute = ({ component: Component, ...rest }) => (

Now the interesting part: we’ll use the isAuth variable to determine if it should redirect or render the protected route’s component.

const ProtectedRoute = ({ component: Component, ...rest }) => (
<AuthConsumer>
{({ isAuth }) => (
<Route
render={
props =>
isAuth
? <Component {...props} />
: <Redirect to="/" />
}
{...rest}
/>

)}
</AuthConsumer>
)

In our index file let’s import ProtectedRoute and use it on our dashboard route.

/* index.js */
...
<ProtectedRoute path="/dashboard" component={Dashboard} />

Awesome, now we have protected routes! Try pointing the browser to /dashboard and watch it kick you back to the landing page.

Again, here’s the link for the working demo. Read more about Context from React’s Official Docs.




 Source : https://medium.com/free-code-camp/how-to-protect-your-routes-with-react-context-717670c4713a