I tried to set an onClick event to open a flexbox in react using tsx. The button and the flexbox is shown properly but vscode shows a problem with the onClick event. I cant figure out whats wrong but maybe you can. I am new to the field and tried some ideas from the stack community but it didnt work for me.
The console tells me I have to assign 'string' but it doesnt work either.
//Function to change visibility of the flexBox
document.getElementById("OpenProfiles")
.addEventListener("click", ProfilesOpn);
function ProfilesOpn () {
var a = document.querySelectorAll(".ProfilesOpen")[0];
var b = document.querySelectorAll(".ProfilesClose")[0];
a.style.visibility = "hidden"
b.style.visibility = "visible";
}
//the button code inside the flexbox
<div className={"Profiles"}>
<div className={"Profile1"}>
<div className={"Profile1P"}></div>
<h3 className={"ProfileH3"}>Profile1</h3>
</div>
<div className={"Profile2"}>
<div className={"Profile2P"}></div>
<h3 className={"ProfileH3"}>Profile2</h3>
</div>
<div className={"Profile3"}>
<div className={"Profile3P"}></div>
<h3 className={"ProfileH3"}>Profile3</h3>
</div>
<div className={"Profile4"}>
<div className={"Profile4P"}></div>
<h3 className={"ProfileH3"}>Profile4</h3>
</div>
<h3 className={"EndCoPro"}>Are you missing any profiles?</h3>
<button id="OpenProfiles" onClick="return(ProfilesOpn());">
<div className={"ProfilesOpen"}><img src={ProfilesOpen} alt="Open Profiles"/></div>
</button>
</div>
//the code in sass for the styling
.Profiles {
position: absolute;
display: flex;
left: 0px;
bottom: 0px;
width: 300px;
height: 900px;
flex-direction: column;
justify-content: flex-start;
align-items: space-between;
background-color: #292929;
box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
border-top-right-radius: 25px;
border-bottom-right-radius: 25px;
visibility: hidden;
}
Code Sandbox: https://codesandbox.io/s/dazzling-bouman-62hgi?file=/src/App.js:0-1850
Here are 2 approaches to what you are trying to accomplish using react hooks:
The ProfilesOpn function uses a ref to set DOM properties.
The reactWayToShowCat function sets the showCat status using internal component state.
import React, { useState, useRef } from "react";
import "./styles.css";
export default function Explorer() {
const a = useRef(null);
const b = useRef(null);
const [showCat, toggleShowCat] = useState(true);
const ProfilesOpn = () => {
a.current.style.visibility = "hidden";
b.current.style.visibility = "visible";
};
const reactWayToShowCat = () => {
toggleShowCat(!showCat);
};
return (
<div className="Profiles">
{Array(4)
.fill("")
.map((_, i) => {
const num = i + 1;
return (
<div className={`Profile${num}`} key={num}>
<div className={`Profile${num}P`}></div>
<h3 className="ProfileH3">{`Profile${num}`}</h3>
</div>
);
})}
<h3 className="EndCoPro">Are you missing any profiles?</h3>
<button id="OpenProfiles" onClick={ProfilesOpn}>
<div className={"ProfilesOpen"} ref={a}>
<img src="https://placekitten.com/200/300" alt="Open Profiles" />
<p>
Click to see solution that uses refs to accomplish what you were
doing
</p>
</div>
</button>
<button id="CloseProfiles" onClick={reactWayToShowCat}>
<div className={"ProfilesClose"} ref={b}>
<>
{showCat && (
<img src="https://placekitten.com/200/300" alt="Close Profiles" />
)}
<p>
Click to see one react way to show and hide the cat (no styling)
</p>
</>
</div>
</button>
</div>
);
}
The main issue in original code was that onClick needs to be set with this syntax:
<button id="OpenProfiles" onClick={ProfilesOpn}>
Hope this helps!
Related
i have a navbar and i want to scroll it horizontally. I use "Tab" and "Tabs" from react-bootstrap. I couldn't figure out how to do this. ( I tried to wrap nav with div, but it didn't work because every tab has its own items )
I tried this:
const outsider = document.getElementsByClassName('products-tabs sub-tabs nav nav-tabs');
const distance = 200;
const scrollLft = () => {
outsider.scrollLeft -= 900;
console.log(outsider);
};
<Tab
className="products-tab"
id="products-tab"
eventKey={index}
title={subcategories.categoryName}
key={`${index + 1}_tab`}
>
{subcategories?.subcategories?.length > 1 ? (
<>
<Button onPress={scrollLft} className="brand-arrow-button">
<i className="icon-Arrow_Simple_left" align="left" />
</Button>
<Button
onPress={() => onClickLeft()}
className="brand-arrow-button-right"
>
<i className="icon-Arrow_simple_rightt" align="left" />
</Button>
<div id="menum">
<Tabs
className="products-tabs sub-tabs"
defaultActiveKey="sub-0"
id="menu-subcategories"
onSelect={e => {
const selectedTabIndex = parseInt(e.split('-')[1], 10);
setActiveSubcategory(selectedTabIndex);
}}
>
{subcategories?.subcategories
?.concat(subcategories?.subcategories)
.map((subcategoryItem, subIndex) => (
<Tab
eventKey={'sub-' + subIndex}
title={subcategoryItem?.name}
key={`${subIndex + 1}_subTab`}
>
**Items
</Tab>
))}
</Tabs>
And this is my css:
&.sub-tabs {
border-radius: 15px;
margin-left: -1px;
margin-right: -16px;
padding-bottom: 1px;
margin-top: 10px;
flex: none;
overflow-x: scroll;
white-space: nowrap !important;
When i click to the button, nothing happens.
This is the console output:
enter image description here
In React, you can use the useRef() Hook to get the reference of a component (similar to document.getElementsByClassName()). Then, you can apply horizontal scrolling using element.current.scrollLeft.
Example:
import { useRef } from 'react'
const App = () => {
const scrollElement = useRef(null)
const scrollLeft = () => {
scrollElement.current.scrollLeft = 50
}
return (
<div className = 'App'>
<div className = 'ScrollMenu' ref = {scrollElement}>
<a href = '#home'>Home</a>
<a href = '#news'>News</a>
<a href = '#contact'>Contact</a>
<a href = '#about'>About</a>
</div>
<button onClick = {scrollLeft}>Click me</button>
</div>
)
}
Here is a live example.
I'm working on a list of items for my website.
I have a list of 5 items with a 'id'. When you click the button, an overlay must be shown with 2 buttons 'change to background to red' and than 'cancel'.
If you click the cancel, the specific 'div class="item"' with the specific id his background must become red.
But, the problem is I don't know how using jquery/javascript to know which button of the div what pressed (button of item id 1 or 2 or 3..)
And also when you click outside the buttons, the overlay must be removed.
Here's the code
$(document).ready(() => {
$('.options-btn').click(function ()
{
var id = $(this).parent().attr('id'); /* find <div class="item"> */
$('body').append('<div class="overlay"></div>');
var append = `
<div class="item-options-active">
<button class="feed-option-btn-number background-btn" tabindex="0">Background set to RED</button>
<button class="feed-option-btn-number cancel-btn" tabindex="0">Cancel</button>
</div>
`;
$(append).appendTo('.overlay');
});
$(document).click(function (e)
{
if (document.getElementsByClassName("overlay").length == 1)
{
if(document.getElementsByClassName("item-options-active").length == 1)
{
// this condition is not working when you click the specific button
if($(".background-btn").data('clicked'))
{
// how to get <div> of the button which was press to change the background??
$('.item').css('background', 'red');
}
}
}
});
})
body {
background: grey;
}
.item {
background: green;
border: 5px solid purple;
margin: 20px;
}
.item button {
margin-left: 10px;
}
.overlay {
position: fixed;
width: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,.85);
z-index: 10000;
}
<body>
<div class="show-items">
<div class="item" id="1">
<button type="button" class="options-btn">check options</button>
</div>
<div class="item" id="2">
<button type="button" class="options-btn">check options</button>
</div>
<div class="item" id="3">
<button type="button" class="options-btn">check options</button>
</div>
<div class="item" id="4">
<button type="button" class="options-btn">check options</button>
</div>
<div class="item" id="5">
<button type="button" class="options-btn">check options</button>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
If you rewrite the .option-btn click event to something like this and delete the document click event it should work:
$('.options-btn').click(function ()
{
var id = $(this).parent().attr('id'); /* find <div class="item"> */
var button = $(this);
$('body').append('<div class="overlay"></div>');
var append = `
<div class="item-options-active">
<button class="feed-option-btn-number background-btn" tabindex="0">Background set to RED</button>
<button class="feed-option-btn-number cancel-btn" tabindex="0">Cancel</button>
</div>
`;
$(append).appendTo('.overlay');
$('.overlay').on('click', function(){
$(this).remove();
}).find('.cancel-btn').on('click', function(){
$(this).closest('.overlay').remove();
});
$('.overlay').find('.background-btn').on('click', function(){
button.closest('.item').css('background', 'red');
$(this).closest('.overlay').remove();
});
});
Working fiddle: https://jsfiddle.net/qntupzj6/
I am using Material UI to create cards that take an argument Actions which is a list of buttons.
The length of the Card is relative to the text I enter, but all Cards will be the same height.
I am very new to CSS and still wrapping my mind around position: fixed, relative, absolute.
This is the code that renders the Card:
export function ViewCurrentPitches2(props) {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onClick={props.closeEditPitch}
/>,
<FlatButton
label="Save"
primary={true}
keyboardFocused={true}
onClick={props.savePitchBeingEdited}
/>,
];
return (
props.state.savedPitches.map((pitch, i) => {
return(
<Card key={pitch.id} className = 'form-margin card-width' zDepth={3}>
<CardText>{pitch.subject} </CardText>
<CardText className='card'>{pitch.pitch}</CardText>
<CardActions>
<FlatButton label="Edit" onClick={(e) => {props.toggleEdit(e, pitch); console.log(props.state.pitchBeingEdited)}}/>
<Dialog
className="dialogBox"
title="Test"
modal={false}
actions={actions}
open={props.state.editPitch}
contentStyle={customContentStyle}
autoScrollBodyContent={true}
>
<TextFieldExampleCustomize currentValue = {props.state.pitchBeingEdited} updateNewPitch = {props.updatePitchBeingEdited} />
</Dialog>
<FlatButton label="Delete" onClick={(e) => {props.deletePitch(e, pitch)}} />
</CardActions>
</Card>
)
})
)
}
<div className='card-parent'>
<ViewCurrentPitches2
state= {this.state}
deletePitch = {this.deletePitch}
handleSave={this.dialogBoxSave}
toggleEdit = {this.toggleEdit}
closeEditPitch = {this.closeEditPitch}
updatePitchBeingEdited = {this.updatePitchBeingEdited}
savePitchBeingEdited = {this.savePitchBeingEdited}
/>
</div>
This is what it looks like:
Can anyone explain to me
1.) When I'm adding in the CSS position: relative | fixed | absolute ...etc what is happening? I assign that to the child correct?
2.) If I want to move the buttons to the bottom of the Card, Card is the parent and I put the styling on the button? How would I go about doing this?
Generally speaking, you would assign relative to the parent and absolute to the child. The child is being positioned absolutely, relative to the parent.
Refer to full documentation for more details.
.card{
display:inline-block;
width:200px;
height: 100px;
border: 1px solid red;
position: relative;
}
.buttons{
position: absolute;
bottom: 0;
border: 1px solid blue;
width: 100%;
}
<div class="parent">
<div class="card">
<div class="buttons">
<button>Edit</button>
<button>Delete</button>
</div>
</div>
<div class="card">
<div class="buttons">
<button>Edit</button>
<button>Delete</button>
</div>
</div>
<div class="card">
<div class="buttons">
<button>Edit</button>
<button>Delete</button>
</div>
</div>
<div>
What I want to do is have something like this:
<button class="addMore">+</button>
Do an effect like this:
https://i.gyazo.com/d353b657df39c0e6ff159bfdb713f6a4.mp4
when you hover over it.
I've been able to find a few different things for this but none that act as I want it to in the video.
Use title in order to display your message:
<button class="addMore" title="click here">+</button>
.addMore{
border: none;
width: 32px;
height: 32px;
background-color: #eee;
transition: all ease-in-out 0.2s;
cursor: pointer;
}
.addMore:hover{
border: 1px solid #888;
background-color: #ddd;
}
<button class="addMore" title="Hover on me!">+</button>
<button type='submit' title='Add New Item'>+</button>
You can set the background color change of button using css as follows,
.addMore:hover {
background-color: #545454; //desired color code
}
and set the tooltip as <button class="addMore" title="click here">+</button>
For all my React.JSers out there, (and for folks that come after), I was able to achieve this by doing (and using the reactstrap lib):
Usage of Tooltip component
import { Button } from 'reactstrap'
<Tooltip
tooltipContent={
'You cannot cancel invoices that were created automatically by memberships!'
}
component={
<span id={'cancelButton'}>
<Button
style={{ pointerEvents: 'none' }}
onClick={...}
disabled
>
Cancel
</Button>
</span>
}
/>
Tooltip.jsx
import React, { useState } from 'react'
import * as Reactstrap from 'reactstrap'
const Tooltip = props => {
const [tooltipOpen, setTooltipOpen] = useState(false)
const toggle = () => setTooltipOpen(!tooltipOpen)
// Warnings for component useage
if (!props.component) {
console.warn('Missing component for tooltip')
}
if (!props.tooltipContent) {
console.warn('Missing content for tooltip')
}
if (props.component && !props.component.props.id) {
console.warn('Component for tooltip has no id (must not have spaces)')
}
return (
<React.Fragment>
{props.component}
{props.tooltipContent && (
<Reactstrap.Tooltip
placement={props.placement ? props.placement : 'top'}
isOpen={tooltipOpen}
target={props.component.props.id}
toggle={toggle}
delay={props.delay ? props.delay : 750}
>
{props.tooltipContent && (
<div className="row p-2">
<div className="col-md-12">{props.tooltipContent}</div>
</div>
)}
</Reactstrap.Tooltip>
)}
</React.Fragment>
)
}
Tooltip.displayName = 'Tooltip'
export default Tooltip
The most important parts are the style={{ pointerEvents: 'none' }} on the <Button /> element and the nesting of the Button within a <span />
var Home = React.createClass({
render: function() {
return (
<div>
<img src="images/12.jpg" />
<img src="images/11.jpg" />
<img src="images/13.jpg" />
<img src="images/14.jpg" />
</div>
)
}
})
I need these 4 images as a slider can anyone give me the code using react or html with CSS
Use ready-made library, here example
https://github.com/jossmac/react-images
https://github.com/xiaolin/react-image-gallery
http://kenwheeler.github.io/slick/
First that is not the way to ask a question. Check here how to ask good question.
You can use some of all made React Slider Components, but if you want to do it on your own you can do something like this :
This is only to get the idea :
class Test extends React.Component {
constructor(){
super();
this.state = {
marginLeft: 0
}
}
componentDidMount(){
this.interval = setInterval(this.changeSlide.bind(this), 2000);
}
changeSlide(){
let totalSlides = document.getElementById("inner").children.length - 1;
let getWidth = document.getElementById("slide1").offsetWidth;
let marginLeft = this.state.marginLeft;
if((totalSlides * -getWidth) >= this.state.marginLeft){
marginLeft = 0
}else{
marginLeft = this.state.marginLeft - getWidth
}
this.setState({marginLeft})
}
render(){
return (
<div className="outter">
<div id="inner" className="inner" style={{marginLeft: this.state.marginLeft}}>
<img src="https://cdn.pixabay.com/photo/2016/12/29/16/12/eiskristalle-1938842_960_720.jpg" style={{maxWidth: "100%"}} id="slide1"/>
<img src="https://cdn.pixabay.com/photo/2014/10/16/09/15/frost-490807_960_720.jpg" style={{maxWidth: "100%"}} id="slide2"/>
<img src="https://cdn.pixabay.com/photo/2015/03/01/07/24/winter-654442_960_720.jpg" id="slide3"/>
</div>
</div>
)
}
}
ReactDOM.render(<Test />, document.getElementById('container'));
.outter{
width: 500px;
overflow: hidden;
}
.inner{
width: 1000%;
float:left;
margin-left: 0;
transition: all 1s ease;
}
.inner img{
max-width: 500px;
width: 500px;
float:left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
In componentDidMount set interval to call the function to change the slide every 2 seconds (in this case).
In function changeSlide first you need to get total slides and the width of the first one (because all have the same width).
Then if it's the last slide set margin-left to 0 and if it's not then subtract the photo width of the current margin-left in the state. At the end update the state.
Hope that this will give you the idea how you can do it.
Here is the fiddle.