How to call a function with arguments onclick of a button in a react component - javascript

Here is my function with arguments that i added in index.html in publics folder in a script tag
function displayContent(event, contentNameID) {
let content = document.getElementsByClassName("contentClass");
let totalCount = content.length;
for (let count = 0; count < totalCount; count++) {
content[count].style.display = "none";
}
let links = document.getElementsByClassName("linkClass");
totalLinks = links.length;
for (let count = 0; count < totalLinks; count++) {
links[count].classList.remove("active");
}
document.getElementById(contentNameID).style.display = "block";
event.currentTarget.classList.add("active");
}
Trying to call this function from click of buttons on my react component that looks like below
<button class="linkClass" onclick="displayContent(event, 'project2')">Meet at Campus
</button>
Please guide me with the syntax

Here's the correct syntax
<button className="linkClass" onClick={(event)=>displayContent(event,'project2')}>Meet at Campus</button>
Edit: please note that React components return JSX

It looks like you're trying to make some sort accordion but you shouldn't really be mixing vanilla JS with React as React needs control of the DOM.
So here's a brief example of how you might approach this using 1) state, and 2) a Panel component which comprises a button, and some content.
const { useState } = React;
function Example() {
// Initialise state with an array of false values
const [ state, setState ] = useState([
false, false, false
]);
// When a button in a panel is clicked get
// its id from the dataset, create a new array using `map`
// and then set the new state (at which point the component
// will render again
function handleClick(e) {
const { id } = e.target.dataset;
const updated = state.map((el, i) => {
if (i === id - 1) return true;
return false;
});
setState(updated);
}
// Pass in some props to each Panel component
return (
<div>
<Panel
name="Panel 1"
active={state[0]}
id="1"
handleClick={handleClick}
>
<span className="text1">Content 1</span>
</Panel>
<Panel
name="Panel 2"
active={state[1]}
id="2"
handleClick={handleClick}
>
<span className="text2">Content 2</span>
</Panel>
<Panel
name="Panel 3"
active={state[2]}
id="3"
handleClick={handleClick}
>
<span className="text3">Content 3</span>
</Panel>
</div>
);
}
function Panel(props) {
// Destructure those props
const {
name,
id,
active,
handleClick,
children
} = props;
// Return a div with a button, and
// content found in the children prop
// When the button is clicked the handler is
// called from the parent component, the state
// is updated, a new render is done. If the active prop
// is true show the content otherwise hide it
return (
<div className="panel">
<button data-id={id} onClick={handleClick}>
{name}
</button>
<div className={active && 'show'}>
{children}
</div>
</div>
);
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
.panel button:hover { cursor: pointer; }
.panel { margin: 1em 0; }
.panel div { display: none; }
.panel div.show { display: block; margin: 1em 0; }
.add { margin-top: 1em; background-color: #44aa77; }
.text1 { color: darkblue; font-weight: 600; }
.text2 { color: darkgreen; font-weight: 700; }
.text3 { color: darkred; font-weight: 300; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Can't you use
document.getElementById("linkClass").onclick = () =>{
displayContent();
}
by giving the element an id with same of the class?

Related

Add className of div clicked on to other specific div

I have the following function component. Within it, when a user clicks on any of the 4 divs, note_b, note_g, note_p, note_y, I want that class name to then be appended to the div with className note
This is my (incomplete) code
import React from 'react-dom';
import DraggableCore from 'react-draggable';
function Note(props) {
return (
<DraggableCore defaultPosition={{x: 1000, y: 200}}>
<div className={"note " + }>
<div id="note_head">
<div id="note_bin"></div>
<div className="note_b" onClick={}></div>
<div className="note_p" onClick={}></div>
<div className="note_g" onClick={}></div>
<div className="note_y" onClick={}></div>
<div id="note_exit"></div>
</div>
<p>
{props.message}
</p>
</div>
</DraggableCore>
)
}
export default Note;
Thank you #Andy, I took a second look at state hooks and came up with this:
import React, { useState } from 'react';
import DraggableCore from 'react-draggable';
function Note(props) {
const [bg, setBG] = useState('note_bg_b');
return (
<DraggableCore defaultPosition={{x: 1000, y: 200}}>
<div className={"note " + bg}>
<div id="note_head">
<div id="note_bin"></div>
<div className="note_b" onClick={() => setBG('note_b')}></div>
<div className="note_p" onClick={() => setBG('note_b')}></div>
<div className="note_g" onClick={() => setBG('note_b')}></div>
<div className="note_y" onClick={() => setBG('note_b')}></div>
<div id="note_exit"></div>
</div>
<p>
{props.message}
</p>
</div>
</DraggableCore>
)
}
export default Note;
This can probably be done in a cleaner, more efficient fashion. It is however functional.
You can use the onClick event handler for each of the four divs and add the className that was clicked on to the div with the className note.
EDIT for additional question: To prevent the added className from unloading when clicking within the note div, we can use an event listener to check where the click originated from and if it did not come from an element with the note_b, note_p, note_g, or note_y className, then the className should not be removed.
import React, { useState, useRef } from 'react';
import DraggableCore from 'react-draggable';
function Note(props) {
const [className, setClassName] = useState('');
const noteDiv = useRef(null);
const handleClick = e => {
setClassName(e.target.className);
}
//This function prevents the default event action from occurring when the page is unloaded.
//If the target element of the event does not have one of the specified class names, it removes the class from the element with the class "note".
const handleUnload = e => {
e.preventDefault();
const noteDiv = document.querySelector('.note');
if (!['.note', 'note_b', 'note_p', 'note_g', 'note_y'].includes(e.target.className)) {
noteDiv.classList.remove(e.target.className);
}
}
return (
<DraggableCore defaultPosition={{ x: 1000, y: 200 }}>
<div ref={noteDiv} className={`note ${className}`} onClick={handleUnload}>
<div id="note_head">
<div id="note_bin"></div>
<div className="note_b" onClick={handleClick}></div>
<div className="note_p" onClick={handleClick}></div>
<div className="note_g" onClick={handleClick}></div>
<div className="note_y" onClick={handleClick}></div>
<div id="note_exit"></div>
</div>
<p>
{props.message}
</p>
</div>
</DraggableCore>
)
}
export default Note;
If you separate out your classes a little, and add a data attribute for each note, you might get closer to what you need.
Instead of a className that looks like node_b use two classes note b - note can be the general class for all notes, and b can be the one that specifies one particular note. I've used colours here for clarity.
Adding the data attribute makes it more easy to identify each note in the code. In the click handler you can destructure that note id from the dataset of the clicked element, and then use it to set state, and you can use that state in the containing element.
Note: I've only used one click handler on the notes' containing element so that I can use event delegation.
const { useState } = React;
function Note({ message }) {
// Initialise a new state to hold the note id
const [ noteClass, setNoteClass ] = useState('');
// The handler first checks to see if the
// clicked element is a "note" element.
// if it is it destructures the note id from the
// element's dataset, and then uses it to set state
function handleClick(e) {
if (e.target.matches('.note')) {
const { note } = e.target.dataset;
setNoteClass(note);
}
}
// When the state changes the containing element's
// class changes too.
return (
<div className={noteClass}>
<div id="note_head">
<div id="note_bin" onClick={handleClick}>
<div data-note="b" className="note b">B</div>
<div data-note="p" className="note p">P</div>
<div data-note="g" className="note g">G</div>
<div data-note="y" className="note y">Y</div>
</div>
<p>{message}</p>
</div>
</div>
);
}
ReactDOM.render(
<Note message="Message" />,
document.getElementById('react')
);
.note { padding: 0.25em; border: 1px solid #4444; }
.note:not(:last-child) { margin-bottom: 0.25em; }
.note:hover { background-color: #fffff0; cursor: pointer; }
.b { color: red; }
.p { color: blue; }
.g { color: green; }
.y { color: gray; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

function in list only works on the first list item in react

I'm looping through a list, every list item has a arrow button that can show a hidden div underneath it. But right now every button triggers the first item in the list.
Im working right now in react, but i cant find the right solution
My JS react file
const CardConference = ({ content }) => {
const showItems = () => {
const items = document.getElementsByClassName("hidden-items")[0];
const arrow = document.getElementsByClassName("arrow-down")[0]
if (items.style.display == "block") {
items.style.display = "none";
arrow.classList.toggle('rotate-arrow')
} else {
items.style.display = "block";
arrow.classList.toggle('rotate-arrow')
}
}
return (
<div className="card card-conferences ">
<h4> {content[0].title} </h4>
<ul>
{content[0].cities.map((city) => (
<div>
<li className="city-name"> {city.name}
<button className="btn button-arrow" onClick={showItems} ><FaAngleDown color="#717171" className="arrow-down" /></button>
</li>
<ul className="hidden-items">
{city.conferenties.map((conf) => (
<li className="hidden-item">{conf} </li>
))}
</ul>
</div>
))}
</ul>
</div >
);
}
export default CardConference;
And this is my css
.arrow-down {
position: absolute;
margin-top: -11px;
margin-left: -6px;
transition: transform 1s;
}
.rotate-arrow {
transform: rotate(180deg);
}
..hidden-items {
display: none;
}
Because you only get getElementsByClassName for first element. You need to pass an index to get exactly the element.
const showItems = (i) => () => {
const items = document.getElementsByClassName("hidden-items")[i];
const arrow = document.getElementsByClassName("arrow-down")[i]
...
cities.map((city, index)
...
onClick={showItems(index)}
...

Is it appropriate to use Document in the react framework?

I have this React component. Which renders a simple HTML. I have an event handler attached to an element. On clicking that particular element I want some CSS styles to change. For that I used the code below-
import React from 'react';
import './start.css';
class Start extends React.Component {
handleEvent() {
const login = document.querySelector('.login');
const start = document.querySelector('.start')
login.style.right = '0';
start.style.left = '-100vw';
}
render() {
return (
<section className = 'page start'>
<h1>Welcome To Our App</h1>
<button onClick = {this.handleEvent}>Next</button>
</section>
)
}
}
export default Start;
My question is in the handleEvent() is it appropriate to select the elements using Document and style the elements using .style. Is there any other "react-specific" way to do this?
class Test extends React.Component {
constructor(){
super();
this.state = {
black: true
}
}
changeColor(){
this.setState({black: !this.state.black})
}
render(){
let btn_class = this.state.black ? "blackButton" : "whiteButton";
return (
<div>
<button className={btn_class}
onClick={this.changeColor.bind(this)}>
Button
</button>
</div>
)
}
}
ReactDOM.render(<Test />, document.querySelector("#app"))
button{
width: 80px;
height: 40px;
margin: 15px;
}
.blackButton{
background-color: black;
color: white;
}
.whiteButton{
background-color: white;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
<div id="app"></div>
first of all yes you can use document in react for that. But "react specific" style you be something like this:
<div id="app"></div>
In css file :
button{
width: 80px;
height: 40px;
margin: 15px;
}
.blackButton{
background-color: black;
color: white;
}
.whiteButton{
background-color: white;
color: black;
}
and finally a component :
class Test extends React.Component {
constructor(){
super();
this.state = {
black: true
}
}
changeColor(){
this.setState({black: !this.state.black})
}
render(){
let btn_class = this.state.black ? "blackButton" : "whiteButton";
return (
<div>
<button className={btn_class}
onClick={this.changeColor.bind(this)}>
Button
</button>
</div>
)
}
}
ReactDOM.render(<Test />, document.querySelector("#app"))
You can set a state to check whether the button has been clicked and change the class name
Similar approach can be used.
This is the React Specific way!
You can refer to React doc
https://reactjs.org/docs/faq-styling.html
import React from 'react';
import './start.css';
class Start extends React.Component {
constructor(props) {
super(props);
this.state = {hasButtonClicked : false};
}
handleEvent() {
this.setState({hasButtonClicked : true});
}
render() {
let clicked = this.state.hasButtonClicked;
return (
<section className = { clicked ? someCssClass :'page start'} >
<h1>Welcome To Our App</h1>
<button onClick = {this.handleEvent}>Next</button>
</section>
)
}
}

Prevent focus on Expand More button after content is inserted in React

I need to list out a long name list inside my page while showing all names at first is not desirable.
So I try to add an expand more button on it.
However, using a button will keep the browser focus on that button after it's pressed, left the button position unchanged on the screen while the name was inserted before that button.
On the other hand, using any, not focusable element (eg. div with onclick function) will do the desired behavior but lost the accessibility at all. Making the "button" only clickable but not focusable.
How do I make the button flushed to list bottom like the snippet div block does? Or is there a better choice to expand the existing list?
const myArray = [
'Alex',
'Bob',
'Charlie',
'Dennis',
'Evan',
'Floron',
'Gorgious',
'Harris',
'Ivan',
'Jennis',
'Kurber',
'Lowrance',
]
const ExpandList = (props) => {
const [idx, setIdx] = React.useState(8)
const handleExpand = e => {
setIdx(idx + 1)
}
return <div className='demo'>
<h1>Name List</h1>
{myArray.slice(0,idx).map(
name => <p key={name}>{name}</p>
)}
<div>
<button onClick={handleExpand} children='Button Expand' className='pointer' />
<div onClick={handleExpand} className='pointer'>Div Expand</div>
</div>
</div>
}
ReactDOM.render(<ExpandList/>, document.getElementById('root'))
.demo>p {
display: block;
padding: 20px;
color: #666;
background: #3331;
}
.demo>div>div {
display: flex;
padding: 15px;
margin-left: auto;
color: #666;
background: #3331;
}
.pointer {
cursor: pointer;
}
.pointer:hover {
background-color: #6663;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id='root' class='demo'>hello</div>
Removing focus from the button in the click handler is probably the most elegant approach: e.target.blur(). It will work on any HTML element, whether it is focusable or not (as with the div in your case).
const myArray = [
'Alex',
'Bob',
'Charlie',
'Dennis',
'Evan',
'Floron',
'Gorgious',
'Harris',
'Ivan',
'Jennis',
'Kurber',
'Lowrance',
]
const ExpandList = (props) => {
const [idx, setIdx] = React.useState(8)
const handleExpand = e => {
e.target.blur()
setIdx(idx + 1)
}
return <div className='demo'>
<h1>Name List</h1>
{myArray.slice(0,idx).map(
name => <p key={name}>{name}</p>
)}
<div>
<button onClick={handleExpand} children='Button Expand' className='pointer' />
<div onClick={handleExpand} className='pointer'>Div Expand</div>
</div>
</div>
}
ReactDOM.render(<ExpandList/>, document.getElementById('root'))
.demo>p {
display: block;
padding: 20px;
color: #666;
background: #3331;
}
.demo>div>div {
display: flex;
padding: 15px;
margin-left: auto;
color: #666;
background: #3331;
}
.pointer {
cursor: pointer;
}
.pointer:hover {
background-color: #6663;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id='root' class='demo'>hello</div>
Inspired by #MiKo, temporally unmount the button after click and set a timeout to add it back seems to do the work. Since browser lose the focus on original expand button, this will keep content flush down without focusing the original button:
const ExpandList = (props) => {
const [idx, setIdx] = React.useState(8)
const [showBtn, setShowBtn] = React.useState(true)
const handleExpand = e => {
setShowBtn(false)
setIdx(idx + 1)
setTimeout(() => setShowBtn(true), 10)
}
return <div className='demo'>
<h1>Name List</h1>
{myArray.slice(0,idx).map(
name => <p key={name}>{name}</p>
)}
{showBtn?
<div>
<button onClick={handleExpand} children='Button Expand' className='pointer' />
<div onClick={handleExpand} className='pointer'>Div Expand</div>
</div> :
<div></div>
}
</div>
}
But I'm still looking a method that doesn't need to 'unmount' a thing which should be there all time.

How to design a multi tab chat with react/redux?

I am developing a chat platform to take multiple chats and he can switch between the chats.
var MessageList = React.createClass({
render() {
return (
<div className='messages'>
<h2> Conversation: </h2>
{
this.props.messages.map((message, i) => {
return (
<Message
key={i}
user={message.user}
text={message.text}
/>
);
})
}
</div>
);
}})
Let's just take an example of message list which will change when user switches the chat tab. Re rendering the same component with new messageList with respect to the chat makes sense but when there are 100 other component changes like this when there is a switch in chat, then there will be lot of repainting/rendering.(I know only diff will be changed in the dom but still.)
I would like to create different elements for different chats and hide and show them based on active chat. But react works under a single dom and replaces the dom with what's returned where it has been attached to.
React.render(<ChatApp/>, document.getElementById('app'));
Can anyone help me up with the design here?
Thanks in advance.
var Tabs = React.createClass({
displayName: 'Tabs',
propTypes: {
selected: React.PropTypes.number,
children: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.element
]).isRequired
},
getDefaultProps: function () {
return {
selected: 0
};
},
getInitialState: function () {
return {
selected: this.props.selected
};
},
shouldComponentUpdate(nextProps, nextState) {
return this.props !== nextProps || this.state !== nextState;
},
handleClick: function (index, event) {
event.preventDefault();
this.setState({
selected: index
});
},
_renderTitles: function () {
function labels(child, index) {
var activeClass = (this.state.selected === index ? 'active' : '');
return (
<li key={index}>
<a href="#"
className={activeClass}
onClick={this.handleClick.bind(this, index)}>
{child.props.label}
</a>
</li>
);
}
return (
<ul className="tabs__labels">
{this.props.children.map(labels.bind(this))}
</ul>
);
},
_renderContent: function () {
return (
<div className="tabs__content">
{this.props.children[this.state.selected]}
</div>
);
},
render: function () {
return (
<div className="tabs">
{this._renderTitles()}
{this._renderContent()}
</div>
);
}
});
var Pane = React.createClass({
displayName: 'Pane',
propTypes: {
label: React.PropTypes.string.isRequired,
children: React.PropTypes.element.isRequired
},
render: function () {
return (
<div>
{this.props.children}
</div>
);
}
});
var App = React.createClass({
render: function () {
return (
<div>
<Tabs selected={0}>
<Pane label="Tab 1">
<div>This is my tab 1 contents!</div>
</Pane>
<Pane label="Tab 2">
<div>This is my tab 2 contents!</div>
</Pane>
<Pane label="Tab 3">
<div>This is my tab 3 contents!</div>
</Pane>
</Tabs>
</div>
);
}
});
ReactDOM.render(<App />, document.querySelector('.container'));
* {
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
}
body {
font: 300 14px/1.4 'Helvetica Neue', Helvetica, Arial, sans-serif;
background: #eee;
margin: 0;
padding: 0;
}
.tabs {
margin: 25px;
background: #fff;
border: 1px solid #e5e5e5;
border-radius: 3px;
}
.tabs__labels {
margin: 0;
padding: 0;
}
.tabs__labels li {
display: inline-block;
}
.tabs__labels li a {
padding: 8px 12px;
display: block;
color: #444;
text-decoration: none;
border-bottom: 2px solid #f5f5f5;
}
.tabs__labels li a.active {
border-bottom-color: #337ab7;
}
.tabs__content {
padding: 25px;
}
<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 class="container"></div>
You are saying redux, so I'll try to give some insight but too lazy to provide any code, since it'll be too big / complex.
Beforehand, if needed, you can use normalizr when handling with nested JSON format since redux love to be immutable and nested makes it harder to be immutable.
The reducers:
chats { userid:"", message:"", time:"" },
users { userid:"", name:"" },
app { selectedUserId:"" }
Now, the number of tabs to be rendered / displayed is equals to number of users. The selected tab is based on app.selectedUserId. The message rendered in panel will be chats, which userid equals app.selectedUserId. Some snippet:
var lo = require('lodash');
var selectedChats = lo.filter(this.props.chats, k => k.userid == app.selectedUserId);
var messagesDom = selectedChats.map(k => <MessageLine chat={k});
var chatTabsDom = this.props.users.map(k => <ChatTab userid={k.userid} className={ k.userid == app.selectedUserId ? "active" : "" }> );
return <div>
<Tabs>{chatTabsDom}</Tabs>
<Messages>{messagesDom}</Messages>
</div>;

Categories