I am new to react js,I am little confused that how to stop triggering simple button from triggering when user clicks Enter Button ...
Sorry my code will be Awkward ...... If it is Uncomfortable to Read Feel free to comment it out
import React from 'react';
import {connect} from 'react-redux';
import {Link} from 'react-router';
import * as headerAction from '../../Actions/headerActions';
import * as notificationActions from '../../Actions/notificationActions';
import * as tagProfileActions from '../../Actions/tagProfileActions';
class TagProfile extends React.Component{
static contextTypes = {
router:React.PropTypes.object
};
constructor(props){
super(props)
this.state = {
data:[],
tagName:"",
In:null,
tagId:"",
tagFollowers:0,
isFollowStatus:""
}
this.handleFollow =this.handleFollow.bind(this)
}
handleFollow(e){
//How to Prevent this
console.log(e.keyCode)//Udefined
e.preventDefault();
console.log('Clicked')
}
render(){
console.log(this.state)
return (
<div className="ContainerForTagProfile">
<div className="TagProfileTopSecTion">
<h1>Topic: {this.state.tagName} </h1>
</div>
<div className="StatusBarRealTimeViewsAndFollowButtn">
<div className="ViewCcountBar">
<p>30,18,5222 👁 </p>
</div>
<div className="FollowButtonForTagPRofile">
<button type="button" onClick={(e)=>this.handleFollow(e)}>{this.state.tagFollowers} | {this.state.isFollowStatus}</button>
</div>
</div>
<div className="GallerySectionForTagforfile">
{this.state.data.map(data => {
return (
<Link key={data.id} href="#" target="_blank" to={'/'+data.postId}><div className="SingleImagePost">
<img src={data.thumNailUrl} />
<div className="LiveViewCountBar">
<p>{data.views} 👁 - {data.whoLikedIt.length} ❤</p>
</div>
<div className="LikesBar">
<div className="MakeItCenter">
<div className="ProfileTinyImage">
<img src={data.postOwnerPic} />
</div>
<div className="ProfilePosTOwnerName">
<p>{data.postOwnerFullName}</p>
</div>
</div>
</div>
</div></Link>
)
})}
</div>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
isLoggedIn:state.logInStatus
}
};
const mapDispatchToProps = (dispatch) => {
return {
getTagProfileData:(slug) => dispatch(tagProfileActions.getTagDetails(slug)),
getTagFollowInfo:slug => dispatch(tagProfileActions.getTagFollowInfo(slug)),
toogleSignInOut:bool => dispatch(headerAction.toggleSignPop(bool)),
popErrorNotification:(bool,color,message) => dispatch(notificationActions.popUpNotification(bool,color,message)),
tagProfileFollow:(data) => dispatch(tagProfileActions.tagProfileFollow(data))
}
};
export default connect(mapStateToProps,mapDispatchToProps)(TagProfile)
Finally I got Solution
Just added KeyDown and Onclick Evt And Throwed some if else statement for KeyBoard Events..
handleFollow(e){
e.preventDefault()
if(e.type !== 'keydown'){
//Start Code From here
}
}
Related
import React,{useState} from 'react'
import { sliderData } from './sliderData'
import ArrowBackIosIcon from '#material-ui/icons/ArrowBackIos';
import ArrowForwardIosIcon from '#material-ui/icons/ArrowForwardIos';
import "./SlideShow.css"
export default function SlideShow() {
const [currentImg,setCurrentImg]=useState(0)
return (
<div >
<h3>SlideShow</h3>
<div className="slideshow" >
<div className="slider" style=
{{backgroundImage:`url(${sliderData[currentImg].image})`}}>
<div className="left"><ArrowBackIosIcon onClick={()=>{currentImg>0 &&
setCurrentImg(currentImg-1)}}/></div>
<div className="center"></div>
<div className="right"><ArrowForwardIosIcon onClick={()=>{
currentImg<sliderData.length-1 && setCurrentImg(currentImg+1)}}/></div>
</div>
</div>
</div>
)
}
I want to make this slideshow automatically moving and pause slideshow on hover .Should not collapse at last image
import React,{useState,useEffect} from 'react'
import { sliderData } from './sliderData'
import ArrowBackIosIcon from '#material-ui/icons/ArrowBackIos';
import ArrowForwardIosIcon from '#material-ui/icons/ArrowForwardIos';
import "./SlideShow.css"
export default function SlideShow() {
const [currentImg,setCurrentImg]=useState(0)
const [hovered,setHovered]=useState(false)
useEffect(() => {
if(!hovered ){
const interval=setTimeout(() => {
const newSlideIndex= currentImg>=sliderData.length-1 ?0:currentImg+1;
setCurrentImg(newSlideIndex );
}, 1000);
return(() => {
})
}
}, [currentImg])
return (
<div >
<h3>SlideShow</h3>
<div className="slideshow" >
<div className="slider" onMouseOver={()=>setHovered(true)}
style=
{{backgroundImage:`url(${sliderData[currentImg].image})`}}>
<div className="left"><ArrowBackIosIcon onClick={()=>
{currentImg>0 && setCurrentImg(currentImg-1)}}/> </div>
<div className="center"></div>
<div className="right" ><ArrowForwardIosIcon onClick={()=>{
currentImg<sliderData.length-1 &&
setCurrentImg(currentImg+1)}}/></div>
</div>
</div>
</div>
)
}
This is pausing on hover but didnt continue sliding after hover
So, im trying to display my component named documentReader inside div with class desktop-app-grid by clicking and icon below, but icon is also a component, i tried doing this by using state, but i don't know how I can do this. I'm dropping my code below with hope someone can help me.
I got this:
<div className="desktop">
<div
className="desktop-app-grid"
>
</div>
<div className="taskbar">
<div className="taskbar-content">
<div className="apps">
<TaskbarAppIcon
appName="documentReader"
icon={icon}
title="My CV"
/>
</div>
<div className="status">
<Clock className="clock" />
</div>
</div>
</div>
</div>
);
}
And on click i want to get displayed in desktop-app-grid like this:
<div
className="desktop-app-grid"
>
<documentReader />
</div>
icon.js (code isn't complete)
class TaskbarAppIcon extends React.Component {
constructor() {
super();
this.state = {
clicked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick = () => {
const icon = document.querySelector("img");
icon.classList.toggle("icon-active");
setTimeout(() => {
icon.classList.toggle("icon-active");
}, 200);
this.setState({
clicked: true
});
}
render(){
const classes = this.props.appName + "Icon icon";
return (
<div className={classes} onClick={this.handleClick}>
<img src={this.props.icon} alt={this.props.appName} title={this.props.title} className="icon-image"></img>
<div className="isActive"></div>
</div>
);
}
}
export default TaskbarAppIcon;
is there any function that works like innerHTML, but isn't a dangerouslyInnerHTML?
what you need to do is move your handleClick and clicked state to the parent component where you rendering TaskbarAppIcon. Being more specific where you have this code:
<div className="desktop">
<div className="desktop-app-grid">
</div>
<div className="taskbar">
<div className="taskbar-content">
<div className="apps">
<TaskbarAppIcon
appName="documentReader"
icon={icon}
title="My CV"
/>
</div>
<div className="status">
<Clock className="clock" />
</div>
</div>
</div>
</div>
So for example, the above code is in you App component, so you need to let it like this:
class App extends React.Component {
constructor() {
super();
this.state = {
clicked: false,
};
this.handleClick = this.handleClick.bind(this);
}
handleClick = () => {
const icon = document.querySelector("img");
icon.classList.toggle("icon-active");
setTimeout(() => {
icon.classList.toggle("icon-active");
}, 200);
this.setState({
clicked: !this.state.clicked,
});
};
render() {
return (
<div className="desktop">
<div className="desktop-app-grid">
// here's the trick, if your clicked state is TRUE it will show <documentReader />
{this.state.clicked && <documentReader />}
</div>
<div className="taskbar">
<div className="taskbar-content">
<div className="apps">
<TaskbarAppIcon
// Here you are specifying that TaskbarAppIcon has a prop handleClick and its a function
handleClick={this.handleClick}
appName="documentReader"
icon={icon}
title="My CV"
/>
</div>
</div>
</div>
</div>
);
}
}
And in your TaskbarAppIcon component you just need to change
<div className={classes} onClick={this.handleClick}>
to
<div className={classes} onClick={this.props.handleClick}>
I know that it is happening because React is re-rendering the page and hence the input field is losing the focus. I have tried everything I could think of but none worked! I can't find a way to resolve the issue.
Here's my React code.
import React, { ChangeEvent, Component, ReactNode } from 'react'
import { Root, /*Routes*/ } from 'react-static'
import { Link } from '#reach/router'
import { Helmet } from 'react-helmet'
import './app.css'
// import FancyDiv from '#components/FancyDiv'
/* According to the following documentation,
* https://github.com/nozzle/react-static/blob/master/docs/concepts.md#writing-universal-node-safe-code
*/
let Sidenav = { init(_: any, options: any) { return {_, options} } }
let updateTextFields = () => {}
if (typeof window !== 'undefined') {
const materialize = require('materialize-css')
Sidenav = materialize.Sidenav
updateTextFields = () => materialize.updateTextFields()
}
interface IComponentProps {
}
interface IComponentState {
'long_url': string
}
const LongUrlInput = (props: any) =>
<input
key='in1'
id="long_url"
type="text"
className="validate"
onChange={ props.handleLongUrl }
/>
export default class App extends Component<IComponentProps, IComponentState> {
constructor(props: any) {
super(props)
this.state = {
'long_url': ''
}
}
componentDidMount(): void {
const elem = document.querySelectorAll('.sidenav')
Sidenav.init(elem, {})
updateTextFields()
}
handleLongUrl = (event: ChangeEvent<HTMLInputElement>): void => {
console.log('types', event.target.value, this.state.long_url)
this.setState({
'long_url': event.target.value
})
}
render(): ReactNode {
return (
<Root>
<Helmet>
<title>ShortURI - URL Shortener</title>
<meta name="description" content="Create short URLs and also monitor traffic with proper analysis report." />
</Helmet>
<nav className={'indigo'}>
<div className="nav-wrapper" style={{ padding: '0 20px' }}>
<Link to={'/'} className={'brand-logo'}>ShortURI</Link>
<a href={''} data-target="slide-out" className="sidenav-trigger">
<i className="material-icons">menu</i>
</a>
<ul id="nav-mobile" className="right hide-on-med-and-down">
<li><Link to={'/about'}>About</Link></li>
<li><Link to={'/#!'}>Login</Link></li>
<li><Link to={'/#!'}>Register</Link></li>
</ul>
</div>
</nav>
<ul id="slide-out" className="sidenav">
<li><a className="sidenav-close" href="#">Clicking this will close Sidenav</a></li>
</ul>
<div className="content">
<div className="row">
<div className="card">
<div className="card-content black-text">
<span className="card-title">Card Title</span>
<div className="input-field col s6">
<LongUrlInput handleLongUrl={this.handleLongUrl}/>
<label className="active" htmlFor="long_url">Long URL</label>
</div>
</div>
</div>
</div>
{/*<FancyDiv>*/}
{/*<Routes/>*/}
{/*</FancyDiv>*/}
</div>
</Root>
)
}
}
PS: I am new to React. Any help would be appreciated.
Note: Typing some random words to suppress StackOverflow Warning - "Looks like your question is mostly code, blah-blah".
I changed <Root>...</Root> to <div>...</div> and somehow it is now working. Weird!
I am using UncontrolledCollapse component from reactstrap and I have multiple static elements to control.
By default I need all the elements to be open by default ( Not collapsed ), on click related individual element will be collapsed.
But I have only one state to manage the behavior, which will open and close all the panels on click.
Below is the code:
import { UncontrolledCollapse, Button, CardBody, Card } from "reactstrap";
class ProductList extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
isOpen: true
};
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
render() {
return (
<div>
<div
className="filter-options-title"
id="toggler"
onClick={this.toggle}
>
Test
</div>
<UncontrolledCollapse toggler="#toggler" isOpen={this.state.isOpen}>
<div className="filter-options-content">Test Content</div>
</UncontrolledCollapse>
<div
className="filter-options-title"
id="toggler1"
onClick={this.toggle}
>
Test
</div>
<UncontrolledCollapse toggler="#toggler1" isOpen={this.state.isOpen}>
<div className="filter-options-content">Test Content</div>
</UncontrolledCollapse>
</div>
);
}
}
You need to create separate keys in your state. Because currently you're using the same state prop for both of the elements, so if you close one both get closed. I also changed the toggle method (made is accept which elements gets toggled).
import { UncontrolledCollapse, Button, CardBody, Card } from 'reactstrap';
class ProductList extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
toggler: true,
toggler1: true,
}
}
toggle(toggler) {
let togglerStatus = this.state[toggler]; //check the status of the toggle you clicked
this.setState({
[toggler]: !togglerStatus // change the status only for the toggle you clicked
});
}
render() {
return (
<div>
<div className="filter-options-title" id="" onClick={() => this.toggle('toggler')}>
Test
</div>
<UncontrolledCollapse toggler="#toggler" isOpen={this.state['toggler']}>
<div className="filter-options-content">
Test Content
</div>
</UncontrolledCollapse>
<div className="filter-options-title" id="toggler1" onClick={() => this.toggle('toggler1')}>
Test
</div>
<UncontrolledCollapse toggler="#toggler1" isOpen={this.state['toggler1']}>
<div className="filter-options-content">
Test Content
</div>
</UncontrolledCollapse>
</div>
)
}
}
In my react app I have this child component that inherits data from its parent. However, it does not update the page with new data from the child component when a relevant anchor link is clicked.
Here's my build - https://suite-search-lk.surge.sh/result/369523
From the link above if you click on a suggested card h1 element it just updates the URL with the id but does not update the page with the relevant card data from that id.
Any idea how I can fix this? Do I have to force the component to re-update?
Parent component (Card Wrapper)
class CardWrapper extends React.Component {
constructor(props) {
super(props);
this.state = {
stories: []
};
}
componentDidMount() {
axios
.get(API)
// .then(response => console.log(response))
// get our stories array, check it and then change state to contain our stories
.then(data => {
let stories;
if (data.data.stories && data.data.stories) {
if (Array.isArray(data.data.stories)) {
stories = data.data.stories;
} else {
stories = [data.data.stories];
}
} else {
stories = [];
}
this.setState({
stories: stories
});
});
}
render() {
return (
<CardWrapperDiv>
<div className="headingWrapper">
<div className="heading"> Suggested for you</div>
</div>
<Cards>
{this.state.stories.map(story => {
return (
<Card
title={story.content.title}
img={story.content.img}
description={story.content.description}
deadline={story.content.deadline_date}
tags={story.content.tags}
key={story.id}
id={story.id}
/>
);
})}
</Cards>
</CardWrapperDiv>
);
}
}
export default CardWrapper;
Child component
class Card extends React.Component {
render() {
return (
<CardDiv>
<div className="cardbox">
<div className="cardDetails">
<div className="headlineText">
<Link to={`/result/${this.props.id}`}> {this.props.title} </Link>
</div>
<div className="headlineSub">Colombo, Sri Lanka</div>
<div className="headlineDes">{this.props.description}</div>
<div className="textRemain">
{" "}
Deadline date: {this.props.deadline}
</div>
<div className="buttonRow">
<button className="downloadBtn">Download</button>
<button className="viewBtn">View</button>
</div>
</div>
<div className="cardimgwrapper">
<div className="cardimg">
<img src={this.props.img} alt="some title" />
</div>
</div>
</div>
</CardDiv>
);
}
}
export default Card;
Sorry it seems I have figured this out using the following post - Can you force a React component to rerender without calling setState?
Although I'm not exactly sure if it's the best way to go about it.
Essentially I used an OnClick listener to run a function and forces a re-render of the entire component.
Hope this can help someone else :)
class Card extends React.Component {
handleButtonClick() {
this.forceUpdate();
}
render() {
return (
<CardDiv>
<div className="cardbox">
<div className="cardDetails">
<div className="headlineText">
<Link to={`/result/${this.props.id}`} onClick={this.handleButtonClick}> {this.props.title} </Link>
</div>
<div className="headlineSub">Colombo, Sri Lanka</div>
<div className="headlineDes">{this.props.description}</div>
<div className="textRemain">
{" "}
Deadline date: {this.props.deadline}
</div>
<div className="buttonRow">
<button className="downloadBtn">Download</button>
<button className="viewBtn">View</button>
</div>
</div>
<div className="cardimgwrapper">
<div className="cardimg">
<img src={this.props.img} alt="some title" />
</div>
</div>
</div>
</CardDiv>
);
}
}
export default Card;
U have to use ur child component as a pure component. PureComponent Update when ur props change.
class Card extends React.PureComponent {
handleButtonClick() {
this.forceUpdate();
}
render() {
return (
<CardDiv>
.....
.....
</CardDiv>
);
}
}
export default Card;