I've been working on React for a few weeks now, and while I've got most of the basic syntax down (props, states), I'm struggling to draw some connections with some concepts, most notably adding classes when a state has changed. I'm trying to build a simon says game, which contains four buttons, all built using a Button component. These are initially set to have a opacity of .3 and an active state of false. When clicked, the state "active" becomes true, but I cannot for the life of me figure out how to add a css class that can give the button a full opacity. Here is my code:
class App extends Component {
constructor(){
super();
this.state = {
active: false
}
}
handleClick(){
this.setState({active: !this.state.active})
}
renderButtons(i, f){
return <Button value={i} className="button" id={f} active= {this.state.active} onClick={() => this.handleClick()}/>
}
render() {
return (
<div className="App">
{this.renderButtons("red", "buttonRed")}
{this.renderButtons("blue", "buttonBlue")}
{this.renderButtons("green", "buttonGreen")}
{this.renderButtons("yellow", "buttonYellow")}
</div>
);
}
}
And my css:
.button{
width: 100px;
height: 45px;
opacity: .3;
margin: 0 auto;
margin-bottom: 30px;
}
#buttonRed{
background: red;
}
#buttonBlue{
background: blue;
}
#buttonGreen{
background: green;
}
#buttonYellow{
background: yellow;
}
So, at this moment, I would simply like to add a class when clicking the button while still keeping the "button" class to the component. Can anyone help?
React has a couple of ways of doing this. The first is as suggested by Tudor Ilisoi, which is simply concatenating strings.
The second way is to give className an Object instead of a string. This way is arguably simpler but requires you to add the classnames module.
You can install it with either npm install --save classnames or yarn add classnames.
You can import it with:
import classNames from 'classnames';
And then you can use it in the following way:
<button className={classNames({button: true, active: this.state.active})} />
The first pair of curly brackets just tells react that we are passing a dynamic property, and the second is just the normal JavaScript syntax for objects.
Note that the object is wrapped by the classNames() function.
If we had declared it earlier, we could just as easily do:
render(){
const classes = classNames({
button: true, // we always want this class
active: this.state.active, // only add this class if the state says so
});
return (
<button className={classes} />
);
}
change className="button" to className={'button ' + f}
The expression enclosed in curly braces is evaluated as javascript and it produces a string
Also note that when using the curly brace syntax you do not have to add double quotes "" around attribute value .
When your JSX is parsed, React will generate the proper HTML attribute, for example class="button red".
if you are looking for 2021/2022 answer:
Here is an example that uses react hooks, which add the class name app to a div element when we click on a Toggle class button.
import React, { useState } from "react";import "./styles.css";
export default function App() {
const [isActive, setActive] = useState("false");
const handleToggle = () => {
setActive(!isActive); };
return (
<div className={isActive ? "app" : null}>
<h1>Hello react</h1>
<button onClick={handleToggle}>Toggle class</button>
</div>
);
}
Have you tried, pass an optional parameter to renderButtons, check it and add to class :
...
renderButtons(i, f, c){
var cssClass = c&&c!=""? "button " + c : "button";
return <Button value={i} className={cssClass} id={f} active= {this.state.active} onClick={() => this.handleClick()}/>
}
...
Related
I'm building an application to save locations i.e countries cities regions etc. When clicking on my on click function the states of two div tags change changing the class name and making one invisible and one visible. advice?
import React, { useState }from "react";
import Area from "../ReadFolder/geographicMainComponents/areaMainComponent.jsx";
import City from "../ReadFolder/geographicMainComponents/cityMainComponent.jsx";
import Country from "../ReadFolder/geographicMainComponents/countryMainComponent.jsx";
import Neighborhood from "../ReadFolder/geographicMainComponents/neighborhoodMainComponent.jsx";
import Region from "../ReadFolder/geographicMainComponents/regionMainComponent.jsx";
import { default as AreaW} from "../WriteFolder/geographicMainComponents/areaMainComponent.jsx";
import { default as CityW} from "../WriteFolder/geographicMainComponents/cityMainComponent.jsx";
import { default as CountryW} from "../WriteFolder/geographicMainComponents/countryMainComponent.jsx";
import { default as NeighborhoodW} from "../WriteFolder/geographicMainComponents/neighborhoodMainComponent.jsx";
import { default as RegionW} from "../WriteFolder/geographicMainComponents/regionMainComponent.jsx";
export default function MenuWrapper({type,id,isEdit}){
let [edit,setEdit] = useState(isEdit);
let changer=()=>{console.log('you clicked me!');setEdit(!setEdit)}
if(type==='country'){
return(
<div key={"frommenulist"+id}>
<div className={edit ? 'd-block' :'d-none'}><CountryW id={id}/><button onClick={changer}>read</button></div>
<div className={edit ? 'd-none' : 'd-block'}><Country id={id} /><button onClick={changer}>edit</button></div>
</div>
);
}
}
It's difficult to work out what clicking those buttons is meant to do. It looks like you need only one div/button block, and clicking the edit button determines what happens (ie to make the country editable somehow).
At the moment it looks like you want to set the display to either block/none but you can't set an element's display to none and still expect to be able to click the button to reset the display because there will be no button to click on. Further: unless the type is "country" the component doesn't return anything so you need a condition in there to return something if type isn't "country" (or add a condition in the parent component to prevent the component rendering at all if that condition is met).
Here's a small example that uses local state to manage whether the div is a plain one or an editable one. Click the edit button, and then click in the div to be able to edit it. You can then click the read button to switch off contentEditable and keep the content.
const { useState } = React;
function MenuWrapper({ type, id }) {
const [ edit, setEdit ] = useState(false);
function handleClick() {
setEdit(!edit);
}
// Return a default div if type is not "country"
if (type !== 'country') return <div>Not country</div>
const divStyle = [
'country',
edit && 'edit'
].join(' ');
return (
<div>
<div>
<div
className={divStyle}
contentEditable={edit}
>Country Id: {id}
</div>
<button onClick={handleClick}>
{edit ? 'Read' : 'Edit'}
</button>
</div>
</div>
);
}
ReactDOM.render(
<MenuWrapper type="country" id="1" />,
document.getElementById('react')
);
.country { padding: 0.25em; }
.edit { border: 1px solid green; }
button { margin-top: 1em; }
<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>
I am new to react and this is my first site and I have some plan JavaScript I found online that will allow a word to be typed out and updated over a course of time. I have already made it into a react Component. But I am not sure how to covert this JavaScript Function into react code.
Here is my new React Component.
import React, {Component} from 'react';
class Hero extends Component {
render () {
return (
<div>
<section id="hero" className="d-flex flex-column justify-content-center align-items-center">
<div className="hero-container" data-aos="fade-in">
<h1>Augusto J. Rodriguez</h1>
<p>I'm a <span className="typed" data-typed-items="opption1, opption2, opption3, opption4"></span></p>
</div>
</section>
</div>
);
}
}
export default Hero;
Here is the vanilla JavaScript that I want to use in my code. Currently this is living in my main.js file that is being called from the index.html. this is the only part of the code that is not working.
if ($('.typed').length) {
var typed_strings = $('.typed').data('typed-items');
typed_strings = typed_strings.split(',')
new Typed('.typed', {
strings: typed_strings,
loop: true,
typeSpeed: 100,
backSpeed: 50,
backDelay: 2000
});
}
I am assuming I need to create a function where my tag is. But I am not sure how to do that in React.
any article references would be awesome or tips on how to resolve this. I have the full code for this project on GitHub.
Looks like that piece of code is using a library called Typed.js.
From looking at your project, I see you setup the Typed.js library inside your public/assets/vendor folder. Instead I would recommend using the NPM package manager to install and setup Typed.js, and copy over the code to work the React way. https://github.com/mattboldt/typed.js/.
Here's an example using Typed.js with React. https://jsfiddle.net/mattboldt/ovat9jmp/
class TypedReactDemo extends React.Component {
componentDidMount() {
// If you want to pass more options as props, simply add
// your desired props to this destructuring assignment.
const { strings } = this.props;
// You can pass other options here, such as typing speed, back speed, etc.
const options = {
strings: strings,
typeSpeed: 50,
backSpeed: 50
};
// this.el refers to the <span> in the render() method
this.typed = new Typed(this.el, options);
}
componentWillUnmount() {
// Make sure to destroy Typed instance on unmounting
// to prevent memory leaks
this.typed.destroy();
}
render() {
return (
<div className="wrap">
<h1>Typed.js</h1>
<div className="type-wrap">
<span
style={{ whiteSpace: 'pre' }}
ref={(el) => { this.el = el; }}
/>
</div>
<button onClick={() => this.typed.toggle()}>Toggle</button>
<button onClick={() => this.typed.start()}>Start</button>
<button onClick={() => this.typed.stop()}>Stop</button>
<button onClick={() => this.typed.reset()}>Reset</button>
<button onClick={() => this.typed.destroy()}>Destroy</button>
</div>
);
}
}
ReactDOM.render(
<TypedReactDemo
strings={[
'Some <i>strings</i> are slanted',
'Some <strong>strings</strong> are bold',
'HTML characters × ©'
]}
/>,
document.getElementById('react-root')
);
It looks like currently you're using the 'typed' library to create this typed list. There are some community packages that act as React wrappers for that, like this one:
https://www.npmjs.com/package/react-typed
Alternatively, you could do what that library does yourself, by loading the 'typed' package in a call to componentDidMount, passing in a React ref instead of a DOM element.
By the way, currently your code uses jQuery (assigned to the variable $) so it's not quite vanilla JS. You could replace the calls to $ with calls to document.querySelector, to make this vanilla JS (though your code might depend on jQuery elsewhere)
New to react and styled-components and have probably got myself in a muddle through not understanding how it all works.
Let's start from the top.
I have a simple page (App.js) that renders two components "Knobs".
I want to pass each 'Knob' one or more properties so it can calculate its size and other relevant instance props. In the example below, one know is 200px in size, and it's sister is a 100px.
import React from 'react';
import Knob from './components/knob.js'
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
hello world
<Knob size={200} />
<Knob size={100} />
</header>
</div>
);
}
export default App;
So far so good.
Now inside the Knob component, I do all my transformations and ultimately have a scaled Knob.
The knob is a svg based component (abbreviated below but still long, sorry).
So - the good news is that it all works! But I know I am approaching this wrong.
In order to get it to work and use the this.state.size to calculate the appropriate font size for the component , I had to move the styled-component object into the class...and create an empty declaration outside the class (Styles).
So - my ask is two-fold:
I think my approach is philosophically damaged...and would love experts here to unscramble my brain.
How would you edit the code to make it not just work, but work right!
a) It seems to me that the entire Styles declaration belongs outside the class.
b) No idea why I have to reference this.state.xxxx twice
c) I think I am also mixing up the use of props and state.
Other than that it's perfect (:. But -- as you see from the screenshot below...it actually works.
Ugh.
import React from 'react'
import { Knob, Pointer, Value, Scale, Arc } from 'rc-knob'
import styled from 'styled-components';
// this is my weird hack to get things working. Declare Styles outside of the class.
var Styles = {}
export default class MyKnob extends React.Component {
constructor(props) {
super(props)
this.state = {
size: props.size,
value: props.value,
radius: (props.value/2).toString(),
fontSize: (props.size * .2)
}
//Now define styles inside the class and i can use the fontsize that is derived from the size passed by the parent component!
Styles = styled.div`
.vpotText {
fill: green;
font-size: ${this.state.fontSize+'px'};
}
`
}
// no idea why I need this block....but without it I get a whole bunch of
// error TS2339: Property 'value' does not exist on type 'Readonly<{}>'.
state = {
value: 50,
size: 100,
radius: '50',
fontSize: 12
}
static defaultProps = { value: 50, size: 100};
render(){
const customScaleTick = ({}) //abbreviated for readability.
return (
<Styles>
<Knob size={this.state.size}
angleOffset={220}
angleRange={280}
steps={10}
min={0}
max={100}
// note use of this.state.value to set parameters that affect the sizing/display of the component
value={this.state.value}
onChange={value => console.log(value)}
>
<Scale steps={10} tickWidth={1} tickHeight={2} radius={(this.state.size/2)*0.84} color='grey' />
<Arc arcWidth={2} color="#4eccff" background="#141a1e" radius = {(this.state.size/2)*0.76} />
<defs>
{/* GRADIENT DEFINITIONS REMOVED FOR READABILITY */}
</defs>
{/* NOTE: EXTENSIVE USE OF this.state.size TO ENSURE ALL PARTS OF THE COMPONENT ARE SCALED NICELY */}
<circle cx={this.state.size/2} cy={this.state.size/2} rx={(this.state.size/2)*0.8} fill = "url(#grad-dial-soft-shadow)" />
<ellipse cx={this.state.size/2} cy={(this.state.size/2)+2} rx={(this.state.size/2)*0.7} ry={(this.state.size/2)*0.7} fill='#141a1e' opacity='0.15' ></ellipse>
<circle cx={this.state.size/2} cy={this.state.size/2} r={(this.state.size/2)*0.7} fill = "url(#grad-dial-base)" stroke='#242a2e' strokeWidth='1.5'/>
<circle cx={this.state.size/2} cy={this.state.size/2} r={(this.state.size/2)*0.64} fill = 'transparent' stroke='url(#grad-dial-highlight)' strokeWidth='1.5'/>
<Pointer width={(this.state.size/2)*0.05} radius={(this.state.size/2)*0.47} type="circle" color='#4eccff' />
{/* THIS IS THE TRICKY ONE! */}
{/* IN ORDER TO GET THE FONT SIZE RIGHT ON THIS ELEMENT (svg) I NEED THE STYLE */}
<Value
marginBottom={(this.state.size-(this.state.fontSize)/2)/2}
className="vpotText"
/>
</Knob>
</Styles>
)}
}
here's a pic of the output:
a) This is how we use props variables in styled components:
const Styles = styled.div`
.vpotText {
fill: green;
font-size: ${props => props.fontSize}px;
};
`;
b) That way you won't need to call the state twice
render(){
return(
<Styles fontSize={this.state.fontSize}>
...
</Styles>
)}
styled-components are really cool once you get the hang of them.
d) Also, I suggest you make value it's own component instead of wrapping it and calling the class.
const StyledValue = styled(Value)`
fill: green;
font-size: ${props => props.fontSize}px;
`;
This looks like it would be a good use case for passing a prop into a Styled Component. It would look something like this:
var Styles = styled.div`
.vpotText {
fill: green;
font-size: ${props => props.size};
}
`
<Styles size={someSize}>
...
</Styles>
You can find the documentation here:
https://styled-components.com/docs/basics#passed-props
I would like to set global style for the react-select. For my understanding I can do 2 ways:
Using className and classNamePrefix and then target elements using CSS.
PROS: I can use the same style everywhere
CONS: Every new component must use exactly the same className and classNamePrefix
Example:
className='react-select-container'
classNamePrefix="react-select"
Result:
<div class="react-select-container">
<div class="react-select__control">
<div class="react-select__value-container">...</div>
<div class="react-select__indicators">...</div>
</div>
<div class="react-select__menu">
<div class="react-select__menu-list">
<div class="react-select__option">...</div>
</div>
</div>
</div>
Create external javascript file with "Provided Styles and State"
PROS: more flexible then CSS
CONS: Every new component must use style property using imported external file.
Example:
const customStyles = {
option: (provided, state) => ({
...provided,
borderBottom: '1px dotted pink',
color: state.isSelected ? 'red' : 'blue',
padding: 20,
}),
control: () => ({
// none of react-select's styles are passed to <Control />
width: 200,
}),
singleValue: (provided, state) => {
const opacity = state.isDisabled ? 0.5 : 1;
const transition = 'opacity 300ms';
return { ...provided, opacity, transition };
}
}
const App = () => (
<Select
styles={customStyles}
options={...}
/>
);
What is the best way to style multiple react-select components? Will be possible to set style globally and every new react-select component use that style automatically?
One way to do it is to create your own select component like CustomSelect that you import instead of react-select where you set for one the custom style or theme like:
import React, { Component } from 'react'
import Select from 'react-select'
class CustomSelect extends Component {
render() {
const styles = {
...
// what ever you need
}
return <Select styles={styles} {...this.props} />
}
}
export default CustomSelect
I can't really tell if it's the best way or not but I've tried both of it and in a big project with many select it's the easiest way to maintain / modify it. Plus it's really convenient if at some point you need to have custom components.
I am using the awesome "Styled-Components"
but I am now using another package that wraps an element inside it so I can't push my StyledComponents there as I don't want to change his package.
I saw glamor has a nice trick.
Is that supported with StyledComponents?
import { css } from 'glamor';
let rule = css({
color: 'red',
})
<div {...rule}>
zomg
</div>
If you think about why I need it, here is an example:
this is an external package I'm using:
External = props => (
<div>
<input style={props.inputStyle} className={props.inputClass} />
</div>
);
so you can see I need to pass in a json style or className
so Glamor will work here, but I dont want to use it just for this scenario.
I'm already enjoying StyledComponent
Thanks
If I understood your query, you can define css rules to a component, like this
import styled from 'styled-components'
const Wrapper = styled.div`
color: 'red';
font-weight: bold;
background-color: ${ props => props.color === 'primary' ? 'green' : 'red' }
`
export const Component = () => {
<Wrapper color='primary'>
I have a red text, and bold font-weight.
</Wrapper>
}