How to import dropdown with autocomplete in the navbar - javascript

Im really new in the react and may be my code is very wrong, but how can create a dropdown with autocomplete in the navbar with bootstrap in React JS.
I read too much examples but my code never run..
I try to create dropdown with create-select but I dont know exactly how..
My code:
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import Select from 'react-select';
import 'react-select/dist/react-select.css';
import PropTypes from 'prop-types';
import createClass from 'create-react-class';
export default class Header extends Component {
var ValuesAsBooleansField = createClass({
displayName: 'ValuesAsBooleansField',
propTypes: {
label: PropTypes.string
},
getInitialState () {
return {
options: [
{ value: true, label: 'Yes' },
{ value: false, label: 'No' }
],
value: null
};
},
onChange(value) {
this.setState({ value });
console.log('Boolean Select value changed to', value);
},
render () {
return (
<div className="section">
<h3 className="section-heading">{this.props.label} (Source)</h3>
<Select
onChange={this.onChange}
options={this.state.options}
simpleValue
value={this.state.value}
/>
<div className="hint">This example uses simple boolean values</div>
</div>
);
}
});
module.exports = ValuesAsBooleansField;
render() {
return (
<nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse ">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">WeatherGraph</a>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Начало <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Времето</a>
</li>
</ul>
</div>
</nav>
);
}
}

You have mixed up the Es5 and Es6 coding style. Just update your code and it's working fine now.
import React, { Component } from 'react';
import Select from 'react-select';
import 'react-select/dist/react-select.css';
export default class ValuesAsBooleansField extends Component {
constructor(props){
super(props);
this.state = {
options: [
{ value: true, label: 'Yes' },
{ value: false, label: 'No' }
],
value: null
}
this.onChange = this.onChange.bind(this);
}
onChange(event) {
this.setState({value: event.value});
console.log('Boolean Select value changed to', event.value);
}
render () {
return (
<div className="section">
<h3 className="section-heading">{this.props.label} (Source)</h3>
<Select
onChange={this.onChange}
options={this.state.options}
value={this.state.value}
/>
<div className="hint">This example uses simple boolean values</div>
</div>
);
}
}
**************** Paste this code in Header.js file *************
import React, { Component } from 'react';
import ValuesAsBooleansField from './ValuesAsBooleansField';
export default class Header extends Component {
render() {
return (
<nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse ">
<button class="navbar-toggler navbar-toggler-right"
type="button" data-toggle="collapse"
data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<ValuesAsBooleansField />
<a class="navbar-brand" >WeatherGraph</a>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link">Начало <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link">Времето</a>
</li>
</ul>
</div>
</nav>
);
}
}

Related

change login to logout when login

i'm following a tutorial to make the navbar changes based if the token is stored in the localstorage or not the problem that when i'm logged , the log in link still in the navbar , but i want to have logout
here is my code :
eventbus.js
<script>
import Vue from 'vue'
const EventBus = new Vue()
export default EventBus
</script>
navbar.vue
<template>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark rounded">
<button class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbar1"
aria-controls="navbar1"
aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse justify-content-md-center" id="navbar1">
<ul class="navbar-nav">
<li class="nav-item">
<router-link class="nav-link" to="/">Home</router-link>
</li>
<li v-if="auth==''" class="nav-item">
<router-link class="nav-link" to="/login">Login</router-link>
</li>
<li v-if="auth==''" class="nav-item">
<router-link class="nav-link" to="/register">Register</router-link>
</li>
<li v-if="auth=='loggedin'" class="nav-item">
<router-link class="nav-link" to="/profile">Profile</router-link>
</li>
<li v-if="auth=='loggedin'" class="nav-item">
<a class="nav-link" href="" v-on:click="logout">Logout</a>
</li>
</ul>
</div>
</nav>
</template>
<script>
import EventBus from './EventBus'
EventBus.$on('logged-in', test => {
console.log(test)
})
export default {
data () {
return {
auth: '',
user: ''
}
},
methods: {
logout () {
localStorage.removeItem('usertoken')
}
},
mounted () {
EventBus.$on('logged-in', status => {
this.auth = status
})
}
}
</script>
login.vue
<template>
<div class="login-page">
<div class="form">
<form #submit.prevent="login">
<input type="text" name="username" v-model="username" placeholder="Username" />
<input type="password" name="password" v-model="password" placeholder="Password" />
<input type="submit" value="LOG IN">
</form>
</div>
</div>
</template>
<script>
import axios from 'axios'
import router from '../router/index'
import EventBus from '../components/EventBus'
import VueCookies from 'vue-cookies'
export default {
data () {
return {
username: '',
password: ''
}
},
methods: {
login () {
axios.post('http://localhost:3001/login',
{
username: this.username,
password: this.password
}
).then((res) => {
console.log(res.data.token)
if(res.data.status===false){
router.push({ name: 'login' })
} else{
localStorage.setItem('usertoken', res.data.token)
this.username = ''
this.password = ''
router.push({ name: 'showgames'})
}
}).catch((err) => {
console.log(err)
})
this.emitMethod()
},
emitMethod () {
EventBus.$emit('logged-in', 'loggedin')
}
}
}
</script>
i would like to know why the navbar didnt change , thank you for your help
The this.emitMethod() statement should be inside the body of .then(...) and yours is outside.
It is also a good practice to use a beforeDestroy() hook in navbar.vue to remove the event handler or otherwise you will have multiple instances of the handler on multiple component mountings (which is quite often during the development).

ReactJs setState undefined when using react-autoBind

Getting this Uncaught TypeError: Cannot read property 'setState' of undefined when trying to setState in a function. I'm aware that there are other similar issues already posted but none of them are using react-autobind
this works when I bind the function in the constructor Like so :
this.toggleNav = this.toggleNav.bind(this)
However I would like to accomplish this with react-autobind
import React from "react";
import ReactDOM from "react-dom";
import ScrollspyNav from "react-scrollspy-nav";
import autoBind from 'react-autobind';
export default class Navigation extends React.Component {
constructor(props) {
super(props);
autoBind(this);
this.state = {
toggleMobileNav: false
};
}
toggleNav() {
this.setState((prev, props) => {
return {
toggleMobileNav: !prev.toggleMobileNav
}
});
}
render() {
return(
<ScrollspyNav
scrollTargetIds={["page-top", "about", "projects", "signup"]}
activeNavClass="is-active"
scrollDuration="1000"
headerBackground="false"
activeNavClass="active-nav"
>
<nav className="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
<div className="container">
<a id="page-top" className="navbar-brand js-scroll-trigger" href="#page-top">Start Bootstrap</a>
<button className="navbar-toggler navbar-toggler-right" onClick={this.toggleNav} type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
Menu
<i className="fas fa-bars"></i>
</button>
<div className= {this.state.toggleMobileNav ? "show collapse navbar-collapse" : " " + 'collapse navbar-collapse'} id="navbarResponsive">
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<a className="nav-link" href="#about">About</a>
</li>
<li className="nav-item">
<a className="nav-link" href="#projects">Projects</a>
</li>
<li className="nav-item">
<a className="nav-link" href="#signup">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
</ScrollspyNav>
)
}
}
If you use arrow function syntax to declare your method, you will not need to call this.toggleNav = this.toggleNav.bind(this) or use react-autobind
toggleNav = () => {
this.setState((prev, props) => {
return {
toggleMobileNav: !prev.toggleMobileNav
}
});
}
Here's a Medium post that covers all the options: https://medium.com/komenco/react-autobinding-2261a1092849

Controlling Modals with States and Props

I am trying to use Reactstrap to create modals that pop up when navigated through the nav bar.
My strategy is to change the state in the parent component and pass them as props to the isOpen attribute to control opening the modals.
The problem is changing the props in the child component doesn't re-render components so I am not able to close the modals!
Parent Controller:
class App extends Component {
constructor(props){
super(props);
this.state = {
zipcode : '',
zipEntered: false
};
this.onZipCodeChange = this.onZipCodeChange.bind(this);
this.isAuth = this.isAuth.bind(this);
}
componentDidMount() {
this.setState({signup:false});
if(this.state.zipcode !== '' || this.state.zipcode !== undefined){
this.setState({zipEntered:true});
this.setState({zipcode:this.state.zipcode});
} else {
this.setState({zipcode: '' });
this.setState({zipEntered:false});
}
}
onZipCodeChange(zip){
//console.log('App has detected ZipCode Change: '+zip);
this.setState({zipcode: zip});
this.setState({zipEntered:false});
}
isAuth(token){
console.log("App has token: "+ token);
//pull data from token
}
render() {
return (
<div className="App">
<header>
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="#">InkSpace</a>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav">
<li className="nav-item">
<a className="nav-link" onClick={() => {this.setState({zipEntered:true})}}>Change Zipcode</a>
</li>
<li className="nav-item">
<a className="nav-link" onClick={() => {this.setState({signup:true})}}>Tattooist</a>
</li>
<li className="nav-item">
<a className="nav-link" href="#">FAQ</a>
</li>
<li className="nav-item">
<a className="nav-link disabled" href="#">Shop</a>
</li>
</ul>
</div>
</nav>
</header>
<ZipCode onSubmit={this.onZipCodeChange} isOpen={this.state.zipEntered} />
<GMap zipcode={this.state.zipcode} />
</div>
);
}
}
export default App;
Child Controller:
class ZipCode extends React.Component {
constructor(props) {
super(props);
this.state = {
zipcode:'' };
this.submitZipCode = this.submitZipCode.bind(this);
this.zipcodeChange = this.zipcodeChange.bind(this);
}
submitZipCode(e){
// console.log('submitting zipcode');
e.preventDefault();
const { onSubmit } = this.props; //pull out to call method it is linked to
onSubmit(this.state.zipcode);
this.setState({isOpen:false});
}
zipcodeChange(e){
this.setState({zipcode: e.target.value});
}
render(){
return(
<div>
<Modal isOpen={this.props.isOpen} toggle={this.toggle} className={this.props.className}>
<ModalHeader toggle={this.toggle}>ZipCode</ModalHeader>
<ModalBody>
<form onSubmit={this.submitZipCode}>
<label>Zip Code</label>
<input
type="input"
name="zipcode"
value={this.state.zipcode}
onChange={this.zipcodeChange}
/>
<Button color="primary" type="submit" className='btn btn-success'>Submit</Button>
</form>
</ModalBody>
</Modal>
</div>
);
}
}
export default ZipCode;

Django/ReactJS how to add django urls as props?

Keep in mind that I am completely fresh with react/django and I need all the help I can get.
I want to create a Navbar component in my application with React. The problem is that the navbar has links to other parts of the application.
What I am trying to do is to pass an array with all the links as props to my navbar component. But how can I get the links in javascript dynamically?
Right now I have this:
index.js:
let navbarUrls = [
{key: 0, url: "{% url 'main:index' %}"}
];
ReactDOM.render(<Navbar urls={navbarUrls} />, document.getElementById('navbar'));
Navbar.js:
import React, {Component} from 'react';
class Navbar extends Component {
render() {
return (
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
{this.props.urls.map(url => (
<a class="navbar-brand" key={url.key} href={url.url}>Main Page</a>
))}
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
</ul>
<div class="navbar-brand">
<div id="current-time">
</div>
</div>
</div>
</nav>
)
}
}
export default Navbar
While the elements are created, the links are of course not since it does not recognize twig... Maybe I am doing this completely wrong? Can someone direct me to the right way??
I am working with React and Django. I have faced a similar type of issue.
const navbarUrls = [
{title: 'TAB-1', path: ''},
{title: 'TAB-2', path: 'tab2'},
{title: 'TAB-2', path: 'tab3'},
];
Lat's Assume these are you links
Now Create a navbar component.
import React, {Component} from 'react';
import {Link} from 'react-router-dom'; // install react-router and react-router-dom version 4.x
class Navbar extends Component {
render() {
return (
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
{this.props.navbarUrls.map(link => (
<Link to={link.path}>{link.title}</Link>
))}
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
</ul>
<div class="navbar-brand">
<div id="current-time">
</div>
</div>
</div>
</nav>
)
}
}
export default Navbar
Now your index.jsx
import * as React from 'react';
import * as ReactDOM 'react-dom';
import {Route, HashRouter, Switch, Redirect} from 'react-router-dom';
import Navbar from 'your-path';
ReactDOM.render(
<HashRouter> // you can use BrowserRoute as well.
<Navbar urls={navbarUrls} />
<Switch>
<Route extact path="/" component={YourComponent1}/>
<Route path="/tab2" component={YourComponent2}/>
<Route path="/tab2" component={YourComponent2}/>
</Switch>
</HashRouter>,
document.getElementById('app')); //id from your main html page.
Please read the doc of react-router https://github.com/ReactTraining/react-router if you are not familiar with it.

Navbar data-toggle and data-target doesn't work

I'm trying to make a responsive navbar.
In desktop shows the NavItems in the NavBar, but in small devices shows the sandwich icon and when we click it should show the same NavItems.
However, when I click on the button, nothing happens.
I was making an adaption of this tutorial:
https://www.youtube.com/watch?v=oUKJA6B1Xr4
The view look like this:
small devices version
desktop version
My NavBar.js
import React, {Component} from 'react';
import NavItems from "./NavItems";
class NavBar extends Component {
render() {
return (
<div>
<nav className="navbar navbar-default panel-app">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse"
data-target="#nav-collapse">
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<a className="navbar-brand" href="#">Hoje para jantar</a>
</div>
<div className="collapse navbar-collapse" id="nav-collapse">
<NavItems className="nav navbar-nav" data-toggle="collapse" data-target=".in" href=""></NavItems>
</div>
</nav>
</div>
);
}
}
export default NavBar;
My NavItems.js
import React, {Component} from 'react';
class NavItems extends Component {
constructor(props) {
super(props);
}
render() {
return (
<ul>
<li className="nav navbar-brand">Receitas</li>
<li className="nav navbar-brand">Por categoria</li>
</ul>
);
}
}
export default NavItems;
I forgot to put the jquery link in the index.html file.
Now it works :)

Categories

Resources