Scroll to particular component in Preact - preact

i am working on preact app and i have different components imported in a single page, i want to click on button in header and scroll to particular component.
this is my parent component
<div class={style.root}>
<Header />
<Landing />
<HowItWorks />
<BrowserCatalogue />
<ContactUs />
<Footer />
</div>
and in my header i have 3 buttons
<div class={styles.headerItems}>
<span style={styles.pointer}>Working</span>
<span style={styles.pointer}>Catalogue</span>
<span style={styles.pointer}>Contact</span>
</div>
</div>
like when i click on working my page should scroll to HowItWorks component.any help?

Let me help you friend. You should introduce refs in your parent component.
We will wrap each section in a div and give it a ref prop.
Here is sandbox for your reference: https://codesandbox.io/s/navbar-click-scroll-into-section-us8y7
Parent Component
import React from "react";
import ReactDOM from "react-dom";
import Header from "./Header";
import HowItWorks from "./HowItWorks";
import BrowserCatalogue from "./BrowserCatalogue";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
selected: null
};
}
//refs
howItWorks = React.createRef();
browserCatalogue = React.createRef();
changeSelection = index => {
this.setState({
selected: index
});
};
componentDidUpdate() {
this.scrollToSection(this.state.selected);
}
scrollToSection = index => {
let refs = [this.howItWorks, this.browserCatalogue];
if (refs[index].current) {
refs[index].current.scrollIntoView({
behavior: "smooth",
block: "nearest"
});
}
};
render() {
return (
<div className="App">
<div>
<Header changeSelection={this.changeSelection} />
</div>
<div ref={this.howItWorks}>
<HowItWorks />
</div>
<div ref={this.browserCatalogue}>
<BrowserCatalogue />
</div>
</div>
);
}
}
Header
const Header = (props) => {
const { changeSelection } = props;
return (
<div style={{ background: "green" }}>
<span onClick={() => changeSelection(0)}>Working</span>{" "}
<span onClick={() => changeSelection(1)}>Catalogue</span>{" "}
<span>Contact</span>
</div>
);
}
Workflow:
Each component gets a ref, and we keep that in memory for when we
need to scroll.
Header, we defined a handler in parent called changeSelection()
and we pass it as prop. It takes an index and we use that index to
update the parent state.
Each link, "Working", "Catalogue", etc, will correspond to an index
that matches with a ref in our parent, so setting up an onClick() handler for each span will allow us to pass in that index to changeSelection()
parent state is updated, triggers componentDidUpdate(), in there
we run scrollToSection() which you guessed it takes in an index (stored in our state as "selected"). Create an array of our refs, and simply use the matching index to locate that ref and scroll to that component.

Related

How to get form data onSubmission in React-remix by using useFetcher Hook using fetcher.submit()

I have a simple component with an input field and a submit button. I just want to get my data after i fill the input field and submit the form. by using useFetcher hook and fetcher.submit().
import { useEffect } from 'react';
import { useFetcher } from '#remix-run/react'
import { ActionFunction } from '#remix-run/node';
function fetchHook() {
const fetch = useFetcher();
useEffect(() => {
console.log("useEffect");
}, []);
return (
<div>
<h1> Use Fetcher Hook</h1>
<fetch.Form action='/fetcher' method='post'>
<div>
<input type="text" name="name" id="" />
<button type='submit' > Submit</button>
</div>
</fetch.Form>
</div>
)
}
export default fetchHook;
export const action: ActionFunction = async ({ request }) => {
}
What changes should i make to get my desired result. I am new to react-remix.

Wrapping code inside styled component in React.js yields unexpected results on show password button click

App.js:
import './App.css';
import React, { Component } from 'react'
import Register from './Components/Register';
import Greet from './Components/Greet';
class App extends Component {
constructor(props) {
super(props)
this.state = {
isRegistered: false,
name: null,
email: null,
password: null,
showPass:false,
}
}
registerHandler=(e) => {
e.preventDefault();
const name = e.target.name.value;
const email = e.target.email.value;
const password = e.target.password.value;
this.setState({ isRegistered: true,name,email,password});
}
showPassHandler=()=>{
this.setState({showPass:!(this.state.showPass)});
}
render() {
return (
<div>
{this.state.isRegistered?<Greet name={this.state.name} email={this.state.email}/>:<Register submit={this.registerHandler} click ={this.showPassHandler} showPass={this.state.showPass}/>}
</div>
)
}
}
export default App;
/////////////////////////////////////////////////////////////
Register.js:
import React,{useState} from 'react'
import Styled from "styled-components";
export default function Register(props) {
const btnStyle={
backgroundColor:"red",
color:"white",
}
// const savePassword=(val)=>{
// show=val.target.value;
// val.target.value=show;
// inputRef.current.focus();
// val.target.focus();
// console.log(show);
// setPass(show);
// }
// console.log(show);
let btnText;
const btnClasses = ["btn","m-1","mt-2"];
if(props.showPass===true)
{
btnStyle.backgroundColor = "green";
btnText="hide password";
btnClasses.push("btn-primary");
}
else{
btnText="show password";
btnClasses.push("btn-danger");
}
const StyledButton = Styled.button
`
background-color: ${(props)=>props.bgColor};
color: white;
display:${(props)=>props.flag==="1"?"inline-block":"block"};
width:${(props)=>props.flag==="1"?"45%":"100%"};
margin:5px;
`
const StyledRegisterContainer = Styled.div`
width:600px;
&:hover {box-shadow:0px 0px 5px grey};
#media (min-width:0px) and (max-width:600px) {
width:300px;
};
`;
//register-container=> was class inside most outer div
return (
<StyledRegisterContainer className='container card mt-4 p-3 '>
<h1 className='text-center'>
Registration Form
</h1>
<form onSubmit={props.submit}>
<div className='form-group'>
<label className='control-label' htmlFor='name'>Name:</label>
<input type='text' name='name' className='form-control'/>
</div>
<div className='form-group'>
<label className='control-label' htmlFor='email'>Email:</label>
<input type='email' name='email' className='form-control'/>
</div>
<div className='form-group'>
<label className='control-label' htmlFor='password'>password:</label>
<input type={props.showPass?"text":"password"} name='password' required className='form-control' />
</div>
<button type='submit' className='btn btn-primary mt-2 m-1'>
Register
</button>
<button type ="button" className={btnClasses.join(" ")} onClick={props.click}>
{btnText}
</button>
<br/>
<StyledButton flag="1" bgColor="orange">Login</StyledButton>
<StyledButton flag="1" bgColor="blue">Login</StyledButton>
<StyledButton flag="0" bgColor="brown">Login</StyledButton>
</form>
</StyledRegisterContainer>
)
}
//style = {btnStyle}//it was inside button =>show password
inside Register.js file everything was working perfect but when I wrapped the code inside StyledRegisterContainer(a styled component) the functionality of show password button is disturbed and the moment I click on show password button the text from input box disapears.
I want my code to work even after wrapping it inside the above mentioned styled component.
I am not familiar with styled-components, but according to their documentation, it seems like you're importing Styled instead of styled
import styled from 'styled-components';
https://styled-components.com/docs/basics#installation

Nextjs: Cant render a component while using map over a array of objects. Objects are not valid as a React child

I dont know why when i want to render a component inside of a map function, basiclly i have a List component, and when i fetch data from an API with the email, etc.. from users i want that component to render that info. But i get the following error:
Unhandled Runtime Error
Error: Objects are not valid as a React child (found: object with keys {email, phone, nick}). If you meant to render a collection of children, use an array instead.
My List component looks like this:
import React from 'react'
export default function List(email, nick, phone) {
return (
<div align="center">
<hr />
<strong>Email: </strong>
<p>{email}</p>
<strong>Nick: </strong>
<p>{nick}</p>
<strong>Phone: </strong>
<p>{phone}</p>
</div>
)
}
And my List user page looks like this:
import React from 'react'
import Nav from '../../components/Nav/Nav'
import { useEffect, useState } from 'react';
import List from '../../components/User/List';
export default function index() {
const [users, setUsers] = useState([])
const fetchUsers = async () => {
const response = await fetch("http://localhost:3001/api/internal/users");
const data = await response.json();
console.log(data["data"])
setUsers(data["data"])
}
useEffect(() => {
fetchUsers()
}, [])
return (
<div>
<Nav />
{users.map(user => (
<List
email={user.attributes.email}
phone={user.attributes.phone}
nick={user.attributes.nick}
/>
))}
</div>
)
}
UPDATE 21 ABR
For some reason when i do this :
export default function List(email, phone, nick) {
return (
<div align="center">
<hr />
<strong>Email: </strong>
<p>{email.email}</p>
<strong>Nick: </strong>
<p>{email.phone}</p>
<strong>Phone: </strong>
<p>{email.nick}</p>
</div>
)
}
It works... Someone knows what it can be?
You are passing the props in a wrong way. Either use it as a single object in props or have all the props it inside {} using destructuring method.
export default function List({email, phone, nick}) {}
OR
export default function List(props) {
return (
<div align="center">
<hr />
<strong>Email: </strong>
<p>{props.email}</p>
<strong>Nick: </strong>
<p>{props.phone}</p>
<strong>Phone: </strong>
<p>{props.nick}</p>
</div>
)
}

"Expected `onClick` listener to be a function, instead got a value of `string` type (ReactJS/MaterialUI)

I create a login button that onClick logs the user in and then the generated information is stored in the local storage, but I keep getting an "Expected onClick listener to be a function, instead got a value of string type. I am using reactJS to do so.
// Global Navigation Bar
import { connect } from "react-redux";
import React, { Component } from "react";
import cognitoUtils from "lib/cognitoUtils";
import "assets/css/Base.css";
import Avatar from "#material-ui/core/Avatar";
import Tooltip from "#material-ui/core/Tooltip";
import AccountCircleOutlinedIcon from "#material-ui/icons/AccountCircleOutlined";
import AccountCircleIcon from "#material-ui/icons/AccountCircle";
const mapStateToProps = state => {
return { session: state.session };
};
class SignInOut extends Component {
onSignOut = e => {
e.preventDefault();
cognitoUtils.signOutCognitoSession();
};
state = {
on: true
};
toggle = () => {
this.setState({
on: !this.state.on
});
};
render() {
return (
<div>
<button className="profile_button" onClick={this.toggle}>
{this.state.on && (
<div>
{this.props.session.isLoggedIn ? (
<div>
<a
className="Home-link"
href="/home"
onClick={this.onSignOut}
>
<Tooltip title="Profile">
<Avatar className="profile_icon">
<AccountCircleIcon className="profile_icon_in" />
</Avatar>
</Tooltip>
</a>
</div>
) : (
<div>
<a
className="Home-link"
href={cognitoUtils.getCognitoSignInUri()}
onClick="/home"
>
<Tooltip title="Profile">
<Avatar className="profile_icon">
<AccountCircleOutlinedIcon className="profile_icon" />
</Avatar>
</Tooltip>
</a>
</div>
)}
</div>
)}
</button>
</div>
);
}
}
export default connect(mapStateToProps)(SignInOut);
Because you are passing String type to onClick
onClick="/home"
You need to pass a function as stated in the error. something like you did before
onClick={this.onSignOut}

Retrieving Geolocation of user without index.html

Hey I'm making a web application that has to track a user location after button is clicked.
I have been using the M.E.R.N stack for this and so far with the tutorials I watched they haven't needed any index.html file just pure JavaScript.
I have implement Google maps on my site without using any HTML files.
This is the code I want to implement
But without having to create a index.html.
How can I add this code to my main.js file without the HTML file?
THIS IS HOW I HAVE GOOGLE MAPS SETUP IN MY LANDING PAGE
import React, { Component } from 'react';
import { Grid, Cell } from 'react-mdl';
import Paper from '#material-ui/core/Paper';
import { Map, GoogleApiWrapper, InfoWindow, Marker } from 'google-maps-react';
//THIS IS THE LANDING PAGE.
const mapStyles = {
width: '100%',
height: '100%'
};
export class LandingPage extends Component {
render() {
return (
<Map
google={this.props.google}
zoom={3}
style={mapStyles}
initialCenter={{
lat: 28.871812,
lng: -34.814106
}}
>
</Map>
);
}
}
export default GoogleApiWrapper({
apiKey: 'API-KEY'
})(LandingPage);
THIS IS NAVBAR WITH THE ENTER CODE BUTTON THAT SHOULD REQUEST GEOLOCATION ON CLICK
importS{}
//THIS IS THE NAVIGATION BAR PAGE.
export default class NavBar extends React.Component {
constructor(props) {
super(props);
this.toggleNavbar = this.toggleNavbar.bind(this);
this.state = {
collapsed: true
};
}
handleClickOpen = () => {
this.setState({ open: true });
};
handleClose = () => {
this.setState({ open: false });
};
toggleNavbar() {
this.setState({
collapsed: !this.state.collapsed
});
}
render() {
return (
<div>
<Navbar style={{background: '#948E99', flex: 1,
background: '-webkit-linear-gradient(to right, #2E1437, #948E99)',
background: 'linear-gradient(to right, #2E1437, #948E99)'}} dark>
<NavbarToggler color="white" onClick={this.toggleNavbar} className="mr-2" />
<Button style={{color: 'white'}} href="/" className="mrauto">DigitalDollar</Button>
<Button style={{color: 'white'}} onClick={this.handleClickOpen} className="mr-auto">Enter Code</Button>
<Dialog
open={this.state.open}
onClose={this.handleClose}
aria-labelledby="form-dialog-title"
>
<DialogTitle id="form-dialog-title">Enter Code</DialogTitle>
<DialogContent>
<DialogContentText>
Thank you for participating in the DigitalDollar global run! By entering this code we will
add your location to our map, please enter your magnificint code here. Thank you for your
participation.
</DialogContentText>
<TextField
autoFocus
margin="dense"
id="Code"
label="Enter Code"
type="Code"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose} color="primary">
Cancel
</Button>
<Button onClick={this.handleClose} color="primary">
Subscribe
</Button>
</DialogActions>
</Dialog>
<Collapse isOpen={!this.state.collapsed} navbar>
<Nav navbar>
<NavItem>
<NavLink href="/">Home</NavLink>
</NavItem>
<NavItem>
<NavLink href="/about">About</NavLink>
</NavItem>
<NavItem>
<NavLink href="https://github.com/CH-SYR3" rel="noopener noreferrer" target="_blank">GitHub</NavLink>
</NavItem>
<NavItem>
<NavLink href="https://www.paypal.com/us/home" rel="noopener noreferrer" target="_blank">Buy Me A Coffee?</NavLink>
</NavItem>
</Nav>
</Collapse>
</Navbar>
<div>
<Navbar color="light" light expand="md">
<Nav className="NavTabs" navbar>
<NavItem>
<NavLink href="/">Map</NavLink>
</NavItem>
<NavItem>
<NavLink href="/time">Time</NavLink>
</NavItem>
<NavItem>
<NavLink href="/hello">Hello</NavLink>
</NavItem>
</Nav>
</Navbar>
</div>
</div>
);
}
It's not a file, just an html5 standard that works in browsers. In the link you provide, the navigation language is in the script tag. If you wrap the navigator.geolocation method in a function getUserLoc() that does little more than setState with the coordinates on click, you will be able to update the map's position by setting state. You'd set the initial state in LandingPage's constructor, then pass `getUserLoc() function to your NavBar component where it can be run with this.props.getUserLoc().
const mapStyles = {
width: '100%',
height: '100%'
};
export class LandingPage extends Component {
constructor(props) {
super(props)
this.state={
lat: 28.871812,
lng: -34.814106
}
this.getUserLoc = this.getUserLoc.bind(this)
}
getUserLoc() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
this.setState({
userLat: pos.lat,
userLng: pos.lng
})
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
render() {
return(
<div>
<Map
google={this.props.google}
zoom={3}
style={mapStyles}
initialCenter={{
lat: this.state.userLat,
lng: this.state.userLng
}}
>
</Map>
<NavBar getUserLoc={this.getUserLoc}/>
</div>
)
}
}

Resources