Reactjs Not able to make a button functional - javascript

I am designing a sidebar for my react project and I have the sidebar which is functioning correctly as expected. As you will see that I have also created a button that will basically open the sidebar from left to right and close it from right to left. But I was not able to make the button functional. Help would be appreciated. Thanks in advance.
[This is what I am getting in the output][1]
[1]: https://i.stack.imgur.com/qnOHz.png
This is the file in which I have the sidebar
import React, { Component } from 'react';
import {NavLink} from 'react-router-dom'
import './TableStyle.css'
class HomePage extends Component {
constructor(props){
super(props);
this.state = {
visible: false
}
}
toggleSidebar(){
this.setState.visible = !this.state.visible
}
render() {
return (
<div id = "sidebar">
<div class = "toggle-btn" onClick = {this.toggleSidebar()}>
<span></span>
<span></span>
<span></span>
<ul>
<NavLink to = "/" style={{color: "white"}}>Home</NavLink>
<p></p>
<NavLink to = "/data" style={{color: "white"}}>Show all entries</NavLink>
</ul>
</div>
</div>
This is TableStyle.css
* {
margin: 0px;
padding: 0px;
font-family: sans-serif;
}
#sidebar {
position: fixed;
width: 200px;
height: 100%;
background: rgb(58, 68, 77);
}
/* #sidebar.active{
left: 0px;
} */
#sidebar ul{
color: rgb(240, 243, 245);
list-style: none;
padding: 15px 10px;
border-bottom: 1px solid rgba(100,100,100,0.3);
transition: all 500ms linear;
}
#sidebar.active{
left: 0px;
}
#sidebar.toggle-btn {
position: absolute;
left: 230px;
top: 30px;
}
#sidebar .toggle-btn span {
display: block;
width: 30px;
height: 3px;
background: white;
margin: 5px 0px;
}

Try using the React Hook useState instead, you don't need an internal state in this case, here is what I would've done:
import React, { Component, useState } from 'react';
import { NavLink } from 'react-router-dom'
import './TableStyle.css'
class HomePage extends Component {
const [visible, setIsVisible] = useState(false);
render() {
return (
<div id="sidebar">
<div class="toggle-btn" onClick={setIsVisible(!visible)}>
<span></span>
<span></span>
<span></span>
<ul>
<NavLink to = "/" style={{color: "white"}}>Home</NavLink>
<p></p>
<NavLink to = "/data" style={{color: "white"}}>Show all entries</NavLink>
</ul>
</div>
</div>
In this way, the button will toggle the visible value from false to true and viceversa. This happens on
<div class="toggle-btn" onClick={setIsVisible(!visible)}>
Where onClick toggles the visible value.
And then use the visible value for example in the following:
<div id="sidebar" class={visible ? "open-sidebar-class" : "close-sidebar-class"}>
The "open-sidebar-class" : "close-sidebar-class" is where you would put the class you want to trigger in the sidebar when the menu opens or closes.
Try then doing this example in TableStyle.css to see if it works, if it does, then just type in the css attributes you want instead to trigger in the sidebar whenever you click the button.
...
.open-sidebar-class {
background-color:green;
}
.close-sidebar-class {
background-color:red;
}
...

Your problem is re-rendering HomePage each time you click on the button, so it resets visibility to false as it executes the component script again. I can't tell why you are re-rendering from the snippet (and please reformat to usual indentation and I couldn't get it to run in a sandbox bc unclosed brackets), but you can work around by passing the sidebar visibility as a prop to the HomePage component.

Related

How to position a div inside another div in reactJs?

I want to put the children div on end of parent div , but positioning is not working. i'm using reactJs, NextJs and styled-components for this code;
reactjs code:
<a href={links[indexImg]} target="_blank" >
<Carousel
image={images[indexImg]}
>
<DescriptionText>
<p>{descriptions[indexImg]}</p>
</DescriptionText>
</Carousel>
</a>
styled-componentes code:
export const DescriptionText = styled.div`
color: white;
background-color: black;
background-position: 20px;
opacity: 0.5;
`;
export const Carousel = styled.div`
position: relative;
border-radius: 50px;
border: solid;
border-width: 3px;
border-color: #C2C2C2;
margin: 0;
height: 100%;
width: 100%;
justify-content: flex-end;
background-size: cover;
background-position: center;
background-image:url(${props => props.image});
`;
If your .inner division has a position of absolute and your .outer one gets position relative, the .inner division will adjust itself inside the .outer one. For example: if you want the .inner one to stick to the bottom of the .outer one you can do this:
.outer {
position: relative
}
.inner {
postion: absolute;
bottom: 0
}
first of all install bootstrap from terminal using the command
npm install react-bootstrap bootstrap
suppose you are working with components like Leftsidebar.js , Rightsidebar.js and Content.js which you have imported to index.js
to do this you have install bootstrap in your react.js
follow the steps
index.js blow
import React from 'react';
import ReactDom from 'react-dom';
import Leftsidebar from './Leftsidebar';
import Rightsidebar from './Rightsidebar';
import Content from './Content';
ReactDom.render(
// outer most div
<div class='row'>
<div class='col-4'>
<Leftsidebar/>
</div>
<div class='col-4'>
<Content/>
</div>
<div class='col-4'>
<Rightsidebar/>
</div>
</div>
,documment.getelementbyId('root');
);
simple we have used the grid system to divide the screen into 4 different part out of 12 secondly the above code is just typed in the text editor .but my aim was to guide you how to show data in different layout or positions using react js and it work because i myself use row column to arrange data in position and it is the easiest method .

Two Components Connected to Each-other

Two of my React components are connected together. You might be thinking, if they are both separate components then they shouldn't be connected, right. WRONG.
What I want to do is this. I want to create a footer but the footer is apparently linked to another component. I think this is a react bug but I have decided not to go there in case it's just my fault. I want to change the width of the footer to be max width with the screen but it doesn't work, it changes both of the components width.
.footer {
width: 100%;
}
.footer {
background-color: gray;
border: 1px solid gray;
border-radius: 1px;
height: 100px;
width: 10000px; /*Or 100%*/
}
.otherComponent {
/*For some reason it copies the same attributes as the css one above (there in different files by the way*/
width: 10000px; /*Or 100%*/ /*The one that got copied by react.*/
background-color: gray;
border: 1px solid gray;
border-radius: 1px;
height: 100px;
}
<div class="otherComponent">
</div>
<br />
<p>This is to demonstrate the bug/error that is happening with my program. And what it looks like</p>
<div class="footer">
</div>
Edit:
I am editing this question since I have received comments saying that this question is not understandable, which I understand. The problem is that I want one of the components (which is a code-box for a documentation website that I am working on) to be somehow separated from another component (which is the footer). Every time I apply a style to the footer component the code-box component is having the same styles.
Information
Both of the different styles for the components are in separate folders. They are separated away from each-other using "<br />" tags. The components are placed like this in the App.js file.
{/* Middle of the page */}
<HomeInfo />
{/* Bottom of the page */}
<Footer />
If this edit still doesn't make sense commenting on the post would help.
As there is little to go on here I'll describe one case where this could occur.
Given the following two components and root app.
Component A:
CSS:
.root {
width: 100%;
}
.component-a-heading {
color: blue;
}
Component:
import React from 'react';
import './component-a.css';
const ComponentA = () => {
return (
<div className="root">
<h1 className="component-a-heading">
I am component A
</h1>
</div>
)
}
export default ComponentB;
Component B:
CSS:
.root {
width: 50%;
}
.component-b-heading {
color: red;
}
Component:
import React from 'react';
import './component-b.css';
const ComponentB = () => {
return (
<div className="root">
<h1 className="component-b-heading">
I am component B
</h1>
</div>
)
}
export default ComponentA;
App:
import React from 'react';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
const App = () => {
return (
<div>
<ComponentA />
<ComponentB />
</div>
);
}
export default App;
The assumed intended result is that:
ComponentA would be 100% width,
ComponentA heading would be blue,
ComponentB would be 50% width,
ComponentB heading would be red.
The reality is that:
ComponentA would be 50% width,
ComponentA heading would be blue,
ComponentB would be 50% width,
ComponentB heading would be red.
This is caused by the fact that even though the CSS unique to each component is imported per component the resulting CSS is global and effects all components that might use the class names defined within (in the example above .root).
Depending on your bundling process you might end up with a single CSS file that
looks something like this:
.root {
width: 100%;
}
.component-a-heading {
color: blue;
}
.root {
width: 50%;
}
.component-b-heading {
color: red;
}
Or you might end up with the styles inserted into the head of your HTML like this:
<style type="text/css">
.root {
width: 100%;
}
.component-a-heading {
color: blue;
}
</style>
<style>
.root {
width: 50%;
}
.component-b-heading {
color: red;
}
</style>
This is a common mistake for people who come from Angular, where imported CSS is scoped to each component, to React.
One way to get around this is to look at the possibility of using CSS Modules which will allow you to locally scope each imported CSS file (this just makes the CSS class names unique in your resulting bundle).
Another option would be to implement a naming policy to ensure that the class names remain unique between components.

How can I have different background color for different component in a React app?

I have never worked with React, Js or CSS. So, I decided to make a very simple Portfolio site with some additional pages. I have planned for having three pages -> Home, About and Portfolio. I have the Home page working as I want it to. I was working on the About page and I realized that whenever I use a custom css for this component with a different background color, it makes it default background color for every component. I'm using routes to jump from one component to the other. I think I'm doing something wrong with routes in index.js. My index.js looks like below,
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router, Route} from 'react-router-dom'
import App from './component/js/App';
import About from './component/js/About'
ReactDOM.render((
<Router>
<div>
<Route path='/' component={App} exact/>
<Route path='/about' component={About} strict/>
</div>
</Router>
), document.getElementById('root'))
I did not create a route for Portfolio since I have not started working on it yet. My App.js looks like below
App.js
import React from 'react';
import Git from '../../images/github.png';
import Email from '../../images/email.png';
import CV from '../../images/resume.png';
import Resume from '../../files/2019.pdf';
import LinkedIn from '../../images/linkedin.png';
import '../css/App.css';
import {NavLink} from 'react-router-dom';
export default class App extends React.Component {
render = () => {
let git_url = 'xxxx'
let Linkedin = 'xxxx'
return (
<div id='main'>
<div id='menu'>
<NavLink id='nav' to='/about'>About</NavLink>
<NavLink id='nav' to='/portfolio'>Portfolio</NavLink>
<NavLink id='nav' to='/home'>Home</NavLink>
</div>
<div id='name'>
<h1 id='pp'>xxxxx</h1>
<h2 id='title'>Engineer / Developer / Designer</h2>
</div>
<div id='contacts'>
<a href={git_url} target='_blank'><img className='nav' id='git' src={Git} /></a>
<a href={Resume} target='_blank'><img className='nav' id='cv' src={CV} /></a>
<a href={Linkedin} target='_blank'><img className='nav' id='cv' src={LinkedIn} /></a>
<img className='nav' id='email' src={Email} />
</div>
</div>
)
}
}
And the css for it looks like below
App.css
body{
background-color: khaki}
#main{
display: flex;
text-align: center;
flex-direction: column;
margin-top: 10%;
}
#menu {
text-align: center;
flex-direction: row;
}
#nav {
padding: 14px 16px;
text-decoration: none;
color: #061A40;
font-size: 20px;
font-weight: bold;
}
#nav:hover {
background-color: #d75f5f;
}
#pp {
color: transparent;
background: url(../../images/background2.jpg) no-repeat center center;
background-size:100%;
-webkit-background-clip: text;
background-clip: text;
margin: 0;
padding: 0;
font-size: 100px;
}
#title {
font-size: 24px;
color: #214F4B;
}
#contacts {
display: flex;
align-self: center;
flex-wrap: wrap;
}
.nav {
height: auto;
width: 50px;
margin: 15px;
transition: transform 3s;
}
.nav:hover{
transform: scale(1.5);
}
I created a test About component to figure out this background-color issue and below is my code,
About.js
import '../css/About.css'
import React from 'react';
export default class About extends React.Component {
render = () => {
return (
<div>
<div id='test'>
<h1>Test</h1>
</div>
<div id='line'></div>
</div>
)
}
}
The css for this looks like below
About.css
body {
background-color:white;
}
#test {
text-align: center;
background-color: #B6C8A9;
padding: 0.01%;
}
h1 {
color: #160C28;
font-family: Arial;
}
In the About.css file, if I have the body{background-color: ...}, every page becomes that color. If I take it out, every page becomes whatever color was set in App.css. As I said, I'm new to JS, CSS and React in general. As I understand, if I include a custom css in the component, it should only apply it to that component. I don't know why it's applying to all the component.
body refers to the whole webpage so it colors the thing which all components are inside of. Further, the CSS in your About.css file is not added/removed when the component is added/removed.
The simplest solution would be to make your About page a div that fills the whole screen and color that.
About.js
export default class About extends React.Component {
render = () => {
return (
<div className="about-page">
<div id='test'>
<h1>Test</h1>
</div>
<div id='line'></div>
</div>
)
}
}
About.css
.about-page {
background-color:white;
min-height: 100vh;
}
#test {
text-align: center;
background-color: #B6C8A9;
padding: 0.01%;
}
h1 {
color: #160C28;
font-family: Arial;
}
The way you have different colors for different components is to use styled-components. You then wrap your components with that styled component. Here is an example:
import styled from 'styled-components'
import style from 'styled-components'
const Div = styled.div`
background-color:#FF7759;
`
const Container = style.div`
background-color:#000000;
`
function Example() {
return (
<div>
<Div>
< Portfolio />
</Div>
<Container>
< Portfolio />
</Container>
</div>
)
}
use style={{ inline css}} props to parent div
example :
<div style={{backgroundColor:'color name here '}}>

How to create Modal Window using React Native?

developers!
I have tried to create a simple Modal Window with React.
But my window still not appeared!
So, my code have two parts: JS-part and CSS-part.
I used "Modal" keyword, constructor and render(). All my code was written in CodePen area, so I'm able to see the result. But still something missing. What is it?
It will be mobile application. So, should I use keyword "Native" somewhere?
import "./modal.scss";
class Modal extends React.Component {
constructor(props) {
super(props);
}
shouldComponentUpdate(nextProps) {
return !I.is(this.props.data, nextProps.data);
}
render() {
let isOpen = this.props.data.get("isOpen");
return (
<div className={`flex middle center modal ${isOpen ? "open" : ""}`}>
{isOpen ?
(<div className={`row modal-content ${this.props.size || ""}`}>
<div className="col-12 middle modal-title">{this.props.title}</div>
<div className="col-12 modal-body">
{this.props.body}
</div>
<div className="col-12 middle modal-footer">{this.props.footer}</div>
</div>) : null
}
</div>);
}
}
export default Modal;
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10000;
padding: 2rem;
background-color: rgba(0, 0, 0, 0.55);
.modal-content {
background-color: white;
max-height: 80%;
height: 80%;
.modal-title {
padding: 0 2.25rem;
height: 5rem;
max-height: 5rem;
text-transform: uppercase;
font-size: 1.8rem;
}
.modal-body {
height: calc(100% - 16rem);
overflow-y: scroll;
padding: 0 2rem;
}
.modal-footer {
height: 5rem;
max-height: 5rem;
padding: 0 2.25rem;
}
}
}
See also a fragment from CodePen:
enter image description here
import Modal from "react-native-modal";
render () {
return (
<View>
<Modal isVisible={true}>
<View style={{ flex: 1 }}>
<Text>I am the modal content!</Text>
</View>
</Modal>
</View>
)
}
See also https://github.com/react-native-community/react-native-modal
I think what you're trying to do is make a mobile application. The best way to do that would be to use React React Native instead of React
Check this out:
https://github.com/react-community/create-react-native-app
Once you're started showing a modal on a screen is quite simple.
https://facebook.github.io/react-native/docs/modal#docsNav
If this is your first time, it would be best to follow the getting started guide on React Native's website. Its helpful. There are no divs, but inLine styling can still be used.
https://facebook.github.io/react-native/docs/getting-started
Hope this helps

Component Not Rendering Properly in React when using CSS hover pseudo selector

My component is a basic NavBar with different items. When Hovering over the item with the dopdiwn-items class, the NavBar should display those items in a block. Instead, only the first item can be seen, with the others being hidden. The same code, when put into plain HTML and CSS on code pen, works as expected. I discovered if I increase the size of the navbar then the items do show as a large block of text. I listed screenshots, and my code below.
CodePen link: http://codepen.io/anon/pen/dvNvmM
Parent Container:
/*Start dependencies*/
import React, { Component, PropTypes } from 'react';
import Picture from '../../components/picture.jsx';
import ShoppingCart from '../../components/shoppingcart.jsx';
import NavBar from '../../components/navbar.jsx';
import { browserHistory } from 'react-router';
import cart from '../../reducers/index.js';
/*Flag set to know if the client recieved and loaded
Will be set to True once the response from the server
Is loaded and parsed*/
var flag = true;
//Start React class
export default class Products extends Component {
constructor(props) {
super(props);
this.state = {clothingData: 0}
}
render(){
/*if the flag variable is false, server is not done yet retriving
data from the DB and parsing it, thus nothing displayed
*/
if (!flag){
return (
<div>
</div>
);
}
//If flag is true (data is ready to be displayed)
else{
//console.log(this.state.clothingData[0].path);
//console.log(this.state.clothingData[0].fileName);
//console.log(this.state.clothingData);
return (
<div>
<NavBar />
<Picture className = "test" src = {this.state.clothingData} onClick = { () => {browserHistory.push('/Product'); }} name = {"joe"} />
</div>
);
}
}
}
JSX:
import React, { Component, PropTypes } from 'react';
export default class NavBar extends Component {
render(){
return(
<ul className="navbar">
<li className="dropdown">
Clothes
<div className="dropdown-items">
Item
Item
Item
Item
</div>
</li>
<li>About</li>
<li>Policies</li>
<li>How To Rent</li>
<li>Contact</li>
</ul>
);
}
}
CSS:
/*Main HTML Stylesheet*/
html{
font-family: sans-serif;
}
/*div{
background:white;
}*/
/********* NavBar Section **********/
.navbar {
overflow: hidden;
background-color:#B597C3;
}
/* links inside the navigation bar */
.navbar li {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: .625em 5em;
text-decoration: none;
font-size: 17px;
}
/* color of links on hover */
.navbar a:hover {
color:#ffffff;
text-decoration: underline;
}
.navbar a.active {
text-decoration:underline;
}
/* Drop Down Items */
.dropdown-btn {
float:left;
font-size: 1.0625em;
color:white;
border: none;
cursor: pointer;
overflow:hidden;
}
.dropdown{
display: inline-block;
}
.dropdown-items{
position:absolute;
display: none;
margin:0;
min-width: 10em;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-items a {
color:white;
padding: 12px 50px;
text-decoration: none;
display: block;
}
.dropdown:hover .dropdown-items {
display: block;
position: absolute;
width: 100%;
height: 100%;
}
/********* NavBar Section **********/
When Hovered:
When Hovered w/ increased size:
Okay, so I think you should not use CSS pseudo selectors with React. I've read questions like this one and my conclusion is in React you should handle the onMouseEnter and onMouseLeave events yourself and then keep a component state that indicates whether the dropdown should be shown or not.
That is the React way of usually doing things: hook up event handler functions and use the component state. When the handler functions are called, you change the state.
I don't know whether CSS pseudo selectors will work properly with React. You can take a look at this GitHub issue. My guess is that whatever you are trying to do doesn't work with the CSS selectors because React uses a virtual DOM and not the actual DOM. So the CSS would be changing the DOM directly kind of thing? It would be nice if other more knowledgeable people could comment on that.
For now, I think you should follow the React way of doing things. Here is the code for what you are trying to do:
import React, { Component, PropTypes } from 'react';
export default class NavBar extends Component {
state = {
showDropdown: false
}
renderDropdown() {
return (
<div className="dropdown-items">
Item
Item
Item
Item
</div>
);
}
render() {
return (
<ul className="navbar">
<li
className="dropdown"
onMouseEnter={() => this.setState({ showDropdown: true })}
onMouseLeave={() => this.setState({ showDropdown: false })}
>
Clothes
{this.state.showDropdown ? this.renderDropdown() : null}
</li>
<li>About</li>
<li>Policies</li>
<li>How To Rent</li>
<li>Contact</li>
</ul>
);
}
}
Keep in mind you should remove the CSS rule for the hover pseudo selector for the items div, as well as the display: none for the dropdown. After doing that, everything should be OK.
Note: I used a property initializer to set up the initial state for the component. Babel should take care of transpiling that. In case that doesn't work, set the initial state in the constructor.

Categories

Resources