Rendering React Components to Specific Div Using Routing - meteor

I am using FlowRouter as a router for a Meteor/React application I am trying to create. I'm having a very hard time trying to get my react components to render in specific places. Does anyone know how to do this?
So on my landing page, when I click a button, I want to route to a secondary page. I have three different components that I want to render in certain parts of the page. I've been using ReactLayout.render(), but I can't seem to make sure components get rendered in certain areas. I thought document.getElementById would work
ReactLayout.render(LandingPage, document.getElementById("landing-page")
but it hasn't been.

The second parameter of ReactLayout.render expects an object. If you want to render several components into your LandingPage element, it might look something like this:
LandingPage = React.createClass({
render() {
return (
<div className="app-root">
<AppHeader />
<div className="container">
{this.props.testOne}
</div>
<div className="app-root">
{this.props.testTwo}
</div>
</div>
);
}
});
Then render using:
FlowRouter.route( '/testRedirect', {
name: 'test',
action() {
ReactLayout.render( Default, { testOne: <TestOneComponent />, testTwo: <TestTwoComponent /> } );
}
});

Related

Next.js: Passing data to nested routes

Issue:
Right now, I have a dynamic route that fetches data using getServerSideProps(). Within this page, there are multiple tabs that renders different data depending on state (which tab is selected).
I wish to transition from using multiple tabs on this page, to instead using nested routes. However, I am having difficulty obtaining the data originally fetched in these nested routes. Is there an efficient way of doing so, without having to call getServerSideProps() again?
My intended setup looks like this, where [page] calls getServerSideProps():
[page].jsx
|_tab1.jsx
|_tab2.jsx
|_tab3.jsx
My current [page].jsx, where I would like to use separate, nested pages that have access to these props (instead of rendering each tab based on state):
export default function Page(props) {
const [currentTab, setCurrentTab] = useState("home");
return (
<div>
<div id="tab1" onClick={() => setCurrentTab("home")}>
home
</div>
<div id="tab2" onClick={() => setCurrentTab("posts")}>
posts
</div>
<div id="tab3" onClick={() => setCurrentTab("info")}>
info
</div>
{currentTab === "home" ? (
<HomeTab props={props}/>
) : currentTab === "posts" ? (
<PostsTab props={props}/>
) : (
<InfoTab props={props}/>
)}
</div>
);
}
Attempts
I've attempted using the context API to utilize data globally, which my other pages can use. However, this requires the user to visit the original dynamic route first.
Call getServerSideProps() on each nested route. Although this works, I wish to find a better solution, since I'm fetching data on each nested route while the route they're nested under has all of this data available already.
You can use shallow routing in next/route or next/link
Note that, in the below example, I'm using next/link for the demonstration. Without your tab data, I'd assume you have an array of tabs in data
import { useEffect } from 'react'
import Link from 'next/link'
//the path is `/tab/:tabId`
function Tab({ data }) {
const [tabData, setTabData] = useState(data[0]) //first tab data as default for example
useEffect(() => {
setTabData(data[tabId])
}, [router.query.tabId])
return <>
<Link href="/tab/0" shallow />
<Link href="/tab/1" shallow />
<div>
{tabData}
</div>
</>
}
export async function getServerSideProps(context) {
return {
props: {
data: [], //tabs' data you fetched from the API
},
}
}
export default Tab

How to make components consist between pages?

When you go to about page from index page, RestOfTheApp rerenders. Maybe it should be this way with SSR, but nextjs added static rendering like gatsby. Isn't there a way to prevent components rerendering? Like: a header shouldn't change between pages.
about.js
function index() {
return (
<>
<RestOfTheApp>
about
</RestOfTheApp>
</>
)
}
index.js
function index() {
return (
<>
<RestOfTheApp>
index
</RestOfTheApp>
</>
)
}
You can keep component state with redux I assume, but whole page re-rendering when you just need to fetch some blog content seems bloaty. I've tested with some basic layout, it still seems lightning fast but not re-rendering whole page is the main concept of SPA's, I am a little heart broken 💔
Every component that you include in a page (under /pages) will re-render no matter what you do. But it's definitely possible to add a persistent layout which doesn't re-render in NextJs. The solution is the custom app component. You can read more about it here
Following example can be helpful to understand how you can create a persistent layout:
// /pages/_app.js
import React from 'react';
import App from 'next/app';
import Layout from '../components/Layout';
class MyApp extends App {
render() {
const { Component, pageProps } = this.props
return (
<Layout>
<Component {...pageProps}></Component>
</Layout>
)
}
}
export default MyApp
In this case, the Layout component will not re-render when you navigate between pages.
#Ankit has already given a great answer on HOW to create a persistent component. Here is WHY it works.
So what really happens when you navigate from some page A (defined in pages/a.js) to another page B (defined in pages/b.js)? First, the navigation takes place on the client-side. This means instead of fetching the rendered HTML from the server, some JavaScript is run in the browser to render the new page. (You can verify it here.) The JavaScript logic of page navigation boils down to this:
The JavaScript code of the new page component <B /> is fetched from the server, if it's not already prefetched;
Next.js will call ReactDOM.render() with 2 arguments: the first one is the new React element to render (it can be roughly thought of as the updated App component), and the second one is the DOM container element (it's always <div id="__next"></div>) that the new React element is rendered into.
In short, this process can be roughly thought of as rendering the updated App component into the <div id="__next"></div> DOM container element. React will then take care of diffing the new and old React elements and decide which part of the DOM to re-render and which part to update.
So what does the new and old React element look like? Well, the default definition of the App component looks like this:
import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
// Component will be set to the current page component
return <Component {...pageProps} />
}
export default MyApp
Where the Component variable will be set to the current page component. This means the old React element will look like this:
<A {...pageProps} />
and the new React element will look like this:
<B {...pageProps} />
According to the React diffing algorithm, when comparing the new and old React element, if the two elements being compared are of different types, then the corresponding subtree will be entirely destroyed and re-rendered.
That's exactly what happens in this case. <A /> and <B /> are two different components and are considered as of different types, so the part of the DOM that corresponds to <A /> will be destroyed and re-rendered as <B />.
That's why the entire page component will be re-rendered when you navigate to a new page, even if they include common components like the header.
If you put the header in the custom App components, like this:
import Header from '../components/header'
function MyApp({ Component, pageProps }) {
return (
<div>
<Header />
<Component {...pageProps} />
</div>
)
}
export default MyApp
Then the <Header /> component will persist across page navigations, because the React diffing algorithm will consider it as the same type and will only make minimal updates to the subtree.

Render a react component on a wordpress page

We currently have our website built with Wordpress and I have built a component in React that we want to conditionally render on the page.
I have the component built and bundled with Webpack for production but cannot figure out how to add it to our website and render the component on the page
edit I will also need to conditionally render the component (form submit, button click, etc.)
Has anyone successfully done this?
Since you've built and bundled your component already, you only need to do three things:
Add the bundled JavaScript (the Webpack output) as a script tag in whatever page you want the component to be on (preferably at the bottom of the <body>).
Example: <script src="wp-content/react/bundle.js"></script>
Add the root element that React will bind to to the same page.
Example: <div id="react-root"></div>
In your component file, render the component to the root element.
Example: ReactDOM.render(<Component />, document.getElementById('react-root'));
To dynamically show and hide the React component based on something that happens outside the component file, you need to create a way to connect the outside (the DOM) to the inside (React). The easiest way to do this is with a global variable attached to window.
In your React component, add the componentWillMount method that defines a global variable:
componentWillMount() {
window.showComponent = (option) => {
// "option" should be true or false
this.setState({ display: option });
}
}
Based on the value passed to setState above, you'll need to add the display property to your component's state:
constructor(props) {
super(props);
this.state = {
display: false
};
}
Now to make the component show or hide based on the value of this.state.display inside the render() method:
render() {
if (this.state.display) {
return (
...
)
} else {
return null;
}
}
All that's left to do is use showComponent(true) or showComponent(false) in your code that handles the form.
In your React project add the file to the global scope (window) like this:
window.myReactComponents = {
myFirstComponent: () => <MyFirstComponent/>
}
Once this is bundled reference the bundlejs file on your non-react page.
In your non react page in the global scope reference ReactDOM.render with the root element which it should use to render like this:
window.useComponent = {
renderMyFirstComponent : ReactDOM.render(
window.myReactComponents.myFirstComponent(),
document.getElementById('myReactElement')
)
};
That's it!
Live example
ReactDOM.render Documentation

METEOR: how to redirect after logout

I am quite new to Meteor & React. Here I would like to redirect my currect user to home page whenever the logout button is pressed. Attached you can see the protected page template with the logout button.
Please note that I am working with the latest versions (Meteor 1.6.1 and React V4).
import React from 'react';
import { Accounts } from 'meteor/accounts-base';
export default class Link extends React.Component{
onLogout(){
Accounts.logout()
};
render(){
return(
<div>
<p>Private Content goes here</p>
<button onClick={this.onLogout.bind(this)}>Logout</button>
</div>
);
}
};
any kind of support will be appreciated.
There are two main options to use here:
1. Pass a callback to Accounts.logout(func)
This is the simplest but mixes the return behavior into your component, which is not ideal.
2. Use Accounts.onLogout(func)
You could put this with your accounts initialization or with your router code, whichever keeps the logic grouped together best for your app.
In that callback, you'll want to use your router to redirect. The exact syntax will depend on your router, but will generally look like:
Router.go('/')
Another way, if you are setting things via meteor-useraccounts way...
const myLogoutFunc = function() {
FlowRouter.go('/login');
}
AccountsTemplates.configure({
// Hooks
onLogoutHook: myLogoutFunc,
onSubmitHook: mySubmitFunc,
preSignUpHook: myPreSubmitFunc,
postSignUpHook: myPostSubmitFunc,
});
Template event code is something like this..
'click .logout': () => {
AccountsTemplates.logout();
}
Read in detail here https://github.com/meteor-useraccounts/core/blob/master/Guide.md

How to expose wrapped <input> in Vue?

I'm trying to create a reusable styled input field in Vue. To make it styled (e.g. with an icon inside) I need to wrap it in another html-element.
Lets call the example below StyledInput
<div class="hasIcon">
<input />
<i class="someIcon"></i>
<div>
If I want to use StyledInput it might look like so:
<styled-input #keyup.enter="doSomething">
</styled-input>
But this would not work, due to the event listener being attached to the <div> instead of the <input>.
A workaround to that could be to emit all key-events from the input field:
<div class="hasIcon">
<input #keyup="$emit('keyup', $event) />
<i class="someIcon"></i>
<div>
But this will not scale well since it would have to be rewritten every time a developer uses an unmapped prop or event.
Is there a way to only make the inner element exposed to whomever uses it?
I'm not sure there is a Vue way to achieve this, because, as far as I'm aware there is no way to bind vue events dynamically, it is however possible to do this using vanilla javascript by passing all events as a prop then mapping them using addEventListener() to add your custom events:
Vue.component('my-input', {
template: "#my-input",
props: ['events'],
mounted() {
// get the input element
let input = document.getElementById('styled-input');
// map events
this.events.forEach((event) => {
let key = Object.keys(event);
input.addEventListener(key, event[key]);
});
}
})
Then you can just pass through all events as a prop like so:
<my-input :events="events"></my-input>
View Model:
var app = new Vue({
el: "#app",
data: {
events: [{
focus: () => {
console.log('focus')
}
}, {
keyup: (e) => {
console.log(e.which)
}
}]
}
})
Heres the JSFiddle: https://jsfiddle.net/h1dnk40v/
Of course, this means any developer would have to do things like map key codes etc, so you will lose some of the convenience Vue provides.
One thing I will just mention is that Vue components aren't necessarily intended to be infinitely reusable, they are supposed to provide specific functionality and encapsulate complex logic, so you would probably do better to implement the most likely use cases, and if the component doesn't fit you can extend it or write a new one for that particular event.
You can also use $attrs to pass props and events onto children elements:
<template>
<div>
<input v-bind="$attrs">
</div>
</template>
In Vue 3, you can specify a second script tag:
<script setup>
</script>
<script>
export default {
inheritAttrs: false,
};
</script>
https://vuejs.org/guide/components/attrs.html#disabling-attribute-inheritance
You could use slots to achieve this. If your <styled-input> template looks like this:
<div class="hasIcon">
<slot><input></slot>
<i class="someIcon"></i>
<div>
Then you can use it like this:
<styled-input>
<input #keyup.enter="doTheThing">
</styled-input>
Or, in cases where you don't care about the input events, like this:
<styled-input></styled-input>
and the default slot content (a bare <input>) will be used. You can use CSS to style the <input> inside the component, but you can't add custom properties or classes to it, so this approach may or may not fit your requirements.

Resources