How to reuse react components in different html pages - javascript

im having problems with re-using react components in two different html pages
heres the structure of my app
react app
|-- webpack.config
|-- package
`-- src
|-- index.js
|-- index.html
|-- home.html
`-- components
|-- Main.js
|-- Sector.js
|-- Homepage.js
okay in webpack.config i have
this
module.exports = {
entry: './index.js',
entry: [
'webpack-dev-server/client?http://127.0.0.1:' + defaultSettings.port,
'webpack/hot/only-dev-server',
'./src/index'
],
output: {
path: path.join(__dirname, '/../dist/assets'),
filename: 'app.js',
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' }
]
}
}
in index.js
import 'core-js/fn/object/assign';
import React from 'react';
import ReactDOM from 'react-dom';
import Appd from './components/Main';
import Sector from './components/sector';
import Homepagesector from './components/Homepagesector';
ReactDOM.render(<Appd />, document.getElementById('app'));
ReactDOM.render(<Sector />, document.getElementById('sector'));
ReactDOM.render(<Homepagesector />, document.getElementById('homepage'));
in index.html
<!doctype html>
<html >
<head>
<meta charset="utf-8">
<title>zilla</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="">
</head>
<!-- REQUIRED 3/3 - the image crop directive -->
<body >
<header>
<div id="app"></div>
</header>
<script src="appcontroller.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>__REACT_DEVTOOLS_GLOBAL_HOOK__ = parent.__REACT_DEVTOOLS_GLOBAL_HOOK__</script>
<script type="text/javascript" src="/assets/app.js"></script>
<script type="text/javascript" src="resample.js"></script>
<script type="text/javascript" src="avatar.js"></script>
</body>
</html>
in home.html
<html>
<head>
</head>
<body >
<header>
<div id="homepage"></div>
</header>
<script src="appcontroller.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>__REACT_DEVTOOLS_GLOBAL_HOOK__ = parent.__REACT_DEVTOOLS_GLOBAL_HOOK__</script>
<script type="text/javascript" src="/assets/app.js"></script>
<script type="text/javascript" src="resample.js"></script>
<script type="text/javascript" src="avatar.js"></script>
<script type="text/javascript" src="avatar.js"></script>
</body>
</html>
In components folder
Main.js
require('styles/App.css');
import React from 'react';
let yeomanImage = require('../images/zilla.png');
class AppComponent extends React.Component {
render() {
return (
<div>
<img src={yeomanImage} alt="Yeoman Generator" />
<h1 className="title"></h1>
<li>
<a href="index2.html" className="a7" >Signin</a>
</li>
<li>
<a href="index.html" className="a7" >Register</a>
</li>
</div>
In components folder
Sector.js
require('styles/sector.css');
import React from 'react';
let yeomanImage = require('../images/dealzilla.png');
let yeomanImaged = require('../images/256.jpg');
class AppComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 'Initial data...'
}
this.updateState = this.updateState.bind(this);
};
updateState(e) {
this.setState({data: e.target.value});
}
render() {
return (
<div className="page-wrap">
<h1>not registered?register for free</h1>
<div className="profile">
<div className="profile-avatar-wrap">
<img src={yeomanImaged} alt="Yeoman Generator" id="profile-avatar" alt="Image for Profile"/>
</div>
<div className="location">upload avatar</div>
</div>
<h3>You could do this with a file input too...</h3>
<div>
<input type = "text" value = {this.state.data}
onChange = {this.updateState} />
<h4>{this.state.data}</h4>
</div>
</div>
In components folder
homepage.js
import React from 'react';
let yeomanImage = require('../images/dealzilla.png');
class AppedComponent extends React.Component {
render() {
return (
<div>
<img src={yeomanImage} alt="Yeoman Generator" />
<h1 className="title">dealzilla</h1>
<li>
<a href="index2.html" className="a7" >Search</a>
<a href="index2.html" className="a7" >Search</a>
</li>
<li>
<a href="index.html" className="a7" >Register</a>
</li>
</div>
);
}
}
AppedComponent.defaultProps = {
};
export default AppedComponent;
The problem is that I am not able to use homepage.js component
in my home.html page
it doesnt appear at all
however my Main.js component is able to appear
Im still a beginner in react, I've looked around for answers and didnt find any on this regard
any help would be appreciated
thank you in advance
best regards

heres what i ended up using maybe it will help someone out there who also got stuck
https://ui-router.github.io/react/
its a great tool to use with react coming from angular

Related

Scripts not working in React, NextJS project unless I specifically refresh the page

I had to refactor a large codebase built on pure HTML, CSS, and javascript into a ReactJS and NextJS application. The codebase had a whole lot of links and scripts whereby some scripts applied for all pages while some applied for only specific pages.
In the set-up I did, I created a Meta.js file where I kept all links and scripts and also created a Layout.js file which held the Meta.js as well a common navbar and sidebar layout which was applied to all pages.
The issue I am facing presently now is that some scripts/functionality do not work unless the page is refreshed. For instance, I enter the application from the homepage which is the index.js file, and then navigate to the settings page, which is a settings.js file.
The settings.js page has some tab that uses some script in it but will not work unless I reload the page. What can be the issue with this and how can I fix this.
Here are some of the important files listed below:
Meta.js
import React from 'react'
import Head from 'next/head'
import Script from 'next/script'
const Meta = ({title, keywords, description}) => {
return (
<>
<Head>
<meta charSet="utf-8" />
<meta content="Webflow" name="generator" />
</Head>
<Script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></Script>
<Script src='/CustomScript.js'></Script>
<Script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js' strategy='beforeInteractive' crossOrigin="anonymous"></Script>
<Script src='/webflow.js'></Script>
<Script src='https://fengyuanchen.github.io/datepicker/js/datepicker.js'></Script>
<Script src='https://cdn.jsdelivr.net/npm/flatpickr'></Script>
<Script src='https://cdn.quilljs.com/1.3.6/quill.js' strategy='beforeInteractive'></Script>
</>
)
}
export default Meta
Layout.js
import Nav from "./Nav";
import Meta from "./Meta";
const Layout = ({children}) => {
return (
<>
<Meta />
<Nav/>
<div className="body">
<main>
{children}
</main>
</div>
</>
);
}
export default Layout;
_app.js
// styles
import '../styles/normalize.css'
import '../styles/webflow.css'
import '../styles/listwise.webflow.css'
import '../styles/styles.css'
// website constant layout
import Layout from '../components/Layout'
function MyApp({ Component, pageProps }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
export default MyApp
Nav.js
import React from 'react'
import Image from 'next/image'
import Link from 'next/link'
const Nav = () => {
return (
<div className="app-nav-layout">
<Link href="#"><Image src="/listwise-logo-black-nospace.svg" width={130} height={130} alt="" className="left-navbar-logo" /></Link>
</div>
<nav role="navigation" className="left-navbar-menu w-nav-menu">
<Link href="/dashboard/listings/addListing">Create new listing</Link>
<Link href="/">Dashboard<br/></Link>
<Link href="/dashboard/listings/allListings"><a className="left-navbar-link w-nav-link"><span className="material-icons-round md-18 mr-8">list_alt</span> Listings<br/></a></Link>
<Link href="/dashboard/settings/settings">Account settings</Link>
<Link href="/dashboard/listings/myListwise">My Listwise</Link>
</nav>
</div>
)
}
export default Nav
settings.js
import React, {useState} from 'react'
import Head from "next/head"
import Script from "next/script"
const settings = () => {
return (
<>
<Head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css" />
<link rel="stylesheet" href="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css" />
<link rel="stylesheet" href="https://unpkg.com/filepond/dist/filepond.min.css" />
<Script src="https://unpkg.com/filepond-plugin-file-encode/dist/filepond-plugin-file-encode.min.js"></Script>
<Script src="https://unpkg.com/filepond/dist/filepond.min.js"></Script>
</Head>
<div className="app-main-layout-container">
<div className="tabs-menu w-tab-menu">
<a data-w-tab="Personal" className="tab-link w-inline-block w-tab-link w--current">
<div className="material-icons-round md-24 icon-acc-settings">person</div>
<div className="tab-text">Personal profile</div>
</a>
<a data-w-tab="Business" className="tab-link w-inline-block w-tab-link">
<div className="material-icons-round md-24 icon-acc-settings">store</div>
<div className="tab-text">Business profile</div>
</a>
<a data-w-tab="Social" className="tab-link w-inline-block w-tab-link">
<div className="material-icons-round md-24 icon-acc-settings">share</div>
<div className="tab-text">Social links</div>
</a>
</div>
<div className="tabs-content w-tab-content">
<div data-w-tab="Personal" className="w-tab-pane w--tab-active">
<div className="w-form">
<form id="wf-form-profile" name="wf-form-profile" data-name="profile" method="get">
<div className="form-group"><label htmlFor="name-4" className="label">Upload profile photo</label>
</form>
</div>
<div data-w-tab="Business" className="w-tab-pane">
<div className="w-form">
<form id="wf-form-profile" name="wf-form-profile" data-name="profile" method="get">
<div className="form-group"><label htmlFor="name-4" className="label">Business name</label>
<div className="hint marginb--20px">This is usually the name you work under</div><input type="text" className="input w-input" maxLength="256" name="Business-Name" data-name="Business Name" placeholder="Enter business name" id="business-name" required="" />
</form>
</div>
<div data-w-tab="Social" className="w-tab-pane">
<div className="w-form">
<form id="wf-form-profile" name="wf-form-profile" data-name="profile" method="get">
<div className="form-group"><label htmlFor="instagram-link" className="label">Instagram profile link</label><input type="text" className="input w-input" maxLength="256" name="Instagram-Link" data-name="Instagram Link" placeholder="www.instagram.com/myname" id="instagram-link" /></div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</>
)
}
export default settings
Also, I will like to ask how best to render those scripts that only work for specific pages, should I add the to the Meta.js file which gets loaded on the initial rendering of the application, or creates a separate file and add it to the page that needs it when the page is navigated to.
The Nextjs Script component can take a strategy prop. It has a default value of afterInteractive which means the script will first load the main javascript that's necessary for the page to become interactive before the script you've linked in the Script tag.
If you need any script to load early because some functionality of your page relies on it you'd want to set the strategy prop to beforeInteractive like so:
<Script src=" ... " strategy="beforeInteractive" />
More information on Next docs
I am also facing this issue but for the time being i just fixed this issue by importing all script code into useEffect here i am removing all events before my script code in useEffect
useEffect(() => {
$(document).ready(function () {
var allElems = $('body').find('*');
allElems.each(function () {
var elm = this, //javascript DOM object
$elm = $(this) //jquery object for element.
$elm.off();
// your script code here
});
});

Vue-Router not rerouting in Single Page Application (Vue/Laravel)

I am trying to get vue-router to work in a Vue.js/Laravel project. I have the following simple pages:
home page:
about page (scrolled down in single page):
Made from these files:
welcome.blade.php:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script crossorigin="anonymous" src="https://polyfill.io/v3/polyfill.min.js?features=WeakMap"></script>
<title>title</title>
</head>
<body id="body">
<div id="app">
<app></app>
</div>
</body>
<script src="{{ mix('js/app.js') }}"></script>
</html>
app.vue:
<template>
<div class="container">
<main>
<home></home>
<about></about>
</main>
</div>
</template>
<script>
import About from "./about"
import Home from "./home";
export default {
name: "app",
components: {
About,
Home,
}
}
</script>
<style lang="scss">
</style>
home.vue:
<template>
<section class="home" style="background-color: yellow; height: 100vh">
<h1>Home Page</h1>
</section>
</template>
<script>
export default {
name: "home"
}
</script>
<style scoped lang="scss">
</style>
about.vue:
<template>
<section class="about" style="background-color: green; height: 100vh">
<h2>About Page</h2>
</section>
</template>
<script>
export default {
name: "about"
}
</script>
<style scoped lang="scss">
</style>
web.php:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
app.js:
require('./bootstrap')
import Vue from "vue"
import App from "../vue/app"
import router from "./router";
const app = new Vue({
el: "#app",
components: { App },
router
})
router.js:
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../vue/home";
import About from "../vue/about";
Vue.use(VueRouter);
export default new VueRouter({
mode: "history",
routes: [
{ path: "/", component: Home},
{ path: "/about", component: About}
]
});
Now, if I add <router-view></router-view> to app.vue like this:
<template>
<div class="container">
<main>
<home></home>
<about></about>
</main>
</div>
<router-view></router-view>
</template>
The site doesn't load at all and the browser console shows no errors:
Path localhost:3000/about shows an 404 Error:
What am I doing wrong?
Did you try to define base in router:
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
});
export default router;
Then in app:
<template>
<div class="container">
<nav>
<router-link
to="/"
tag="a"
>Home</router-link>
<router-link
to="/about"
tag="a"
>About</router-link>
</nav>
</div>
<router-view></router-view>
</template>
In Laravel you need a catch-all route that redirects all routes to your Vue project:
Create a new controller called something like VueController, then direct all your routes in Laravel to it:
Route::get('/{any}', 'VueController#index')->where('any', '.*');
Then in your VueController return your welcome blade:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class VueController extends Controller
{
public function index()
{
return view('welcome');
}
}

Vue router is not routing

When directing to '/' the "mainapp im here" message is showing but the routing
to homepage is not happening , below is my code , this is my first time using Vue
and im trying to work with it, the problem it's not routing note that
it's accessing the router.js
----- web.php
// Client Routes
Route::get('/', 'Client\HomeController#index');
----- HomeController.php
<?php
namespace App\Http\Controllers\Client;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Package;
class HomeController extends Controller
{
public function index()
{
return view('client.home.index');
}
}
----- Index.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
</head>
<body>
<div id="app">
<mainapp> </mainapp>
</div>
</body>
<script src="./js/app.js"></script>
</html>
----- mainapp.vue
<template>
<div>
<h1>mainapp im heree</h1>
<router-view> </router-view>
</div>
</template>
----- Router.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
import homePage from './components/pages/homePage.vue'
const routes =[
{
path:'/',
component: homePage
}
]
export default new Router ({
mode: 'history',
routes
})
-----app.js
require('./bootstrap');
window.Vue = require('vue');
import router from './router'
Vue.component('mainapp', require('./components/mainapp.vue').default);
const app = new Vue({
el: '#app',
router
})
-----Homepage.vue
<template>
<div>
<h1>hello</h1>
</div>
</template>

Laravel + Vue spa two step router not working

Laravel: 7.17, Vue: 2.5.17.
I made simple sidebar and tried to work that.
One step router ( /admin, /home, /... ) worked well but two steps router(/admin/blog/category, /admin/blog/post...) didn't work.
Here is what I did.
-routes/web.php
Route::get('/{any?}', function() {
return view('app');
})->where('any', '.*');
-resources/views/app.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<link rel="stylesheet" href="/css/app.css">
</head>
<body>
<div id="app">
<div class="container mx-auto">
<main class="d-flex">
<aside class="w-25">
<section>
<ul>
<li><router-link to="/admin">Dashboard</router-link></li>
</ul>
</section>
<section>
<h6>Blog </h6>
<ul class="list-group">
<li><router-link to="/admin/blog/category">Category</router-link></li>
<li><router-link to="/admin/blog/post">Posts</router-link></li>
</ul>
</section>
</aside>
<div class="p-3">
<router-view></router-view>
</div>
</main>
</div>
</div>
<script src="/js/app.js"></script>
</body>
</html>
-resources/js/app.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes';
Vue.use(VueRouter);
const app = new Vue({
el: '#app',
router: new VueRouter(routes)
});
-resources/js/routes.js
import Home from './components/Home';
import Admin from './components/admin/Admin';
import Category from './components/admin/blog/Category';
import Post from './components/admin/blog/Post';
import PathThrough from './components/PathThrough';
export default {
mode:'history',
routes:[
{
path:'/',
component: Home
},
{
path:'/admin',component: Admin,
children: [
{
path:'blog', component: PathThrough,
children: [
{ path: 'category', component: Category},
{ path: 'post', component: Post},
]
}
]
},
]
};
-resources/js/components/PathThrough.vue
<template>
<router-view></router-view>
</template>
<script>
export default {};
</script>
-other components
<template>
<h1>Home Page</h1>
</template>
<script>
export default {};
</script>
Here, /admin and / routes are working.
But other routes don't work.
Can anyone help me?
Thank you!

I've got "Target container is not a DOM element" error on my codesandbox with react & parcel

My project was working on my computer but now on CodeSanbox I've got an error
Target container is not a DOM element
The project is just a template project using react & parcel.
I didn't change anything between my home project and the one on codesanbox.
<!DOCTYPE html>
<html>
<head>
<title>React App w/ Parcel</title>
<meta charset="utf-8" />
</head>
<body>
<div id="app"></div>
<script src="index.js"></script>
</body>
</html>
import React from "react";
import ReactDOM from "react-dom";
import "./styles.scss";
const App = () => {
return <div />;
};
ReactDOM.render(<App />, document.getElementById("app"));
github repo
There seems to be a clash with the keyword app.
You can simply rename the div to root or similar
<!DOCTYPE html>
<html>
<head>
<title>React App w/ Parcel</title>
<meta charset="utf-8" />
</head>
<body>
<div id="root"></div>
<script src="index.js"></script>
</body>
</html>
import React from "react";
import ReactDOM from "react-dom";
import "./styles.scss";
const App = () => {
return <div />;
};
ReactDOM.render(<App />, document.getElementById("app"));
Working sandbox: https://codesandbox.io/s/react-app-parcel-g9ff8

Categories

Resources