How can i add a dynamic class in react? - reactjs

Here the width is mentioned inline so i want to make a card component where the width can be handled dynamically. what i mean to say is there will be one card component from which i can handle the width property dynmically through jsx suppose for one card the width is 250px and for another card the width might be 100px like this
<div className="white-box v-align ht-100" style={{ width: '250px', marginRight: '10px' }}>
<div className="flex-one"></div>
<div className="wd-80">
<div className="fs-xl fw-bold" style={{ color: '#142654' }}>{pct}%</div>
<div className="small-text">{text}</div>
</div>
</div>

A solution to this problem might be using props:
// SomeComponent.js class
class SomeComponent {
// Uncomment if you need to set a state
//constructor(props) {
// super(props);
//
// this.state = {};
//}
render() {
let width = Math.min(Math.max(this.props.width, SOME_MAX_WIDTH), SOME_MIN_WIDTH); // clamp (optional)
return ( // replace with your component
<div style={{width: width, backgroundColor: "#23a4f6"}}>
Width set from parent (and clamped)
</div>
);
}
}
SomeComponent.defaultProps = {
width: 200
};
// SomeComponent.js in functional
function SomeComponent({width}) {
let width = Math.min(Math.max(this.props.width, SOME_MAX_WIDTH), SOME_MIN_WIDTH); // clamp (optional)
return ( // replace with your component
<div style={{width: width, backgroundColor: "#23a4f6"}}>
Width set from parent (and clamped)
</div>
);
}
SomeComponent.defaultProps = {
width: 200
};
// main.js
ReactDOM.render(<SomeComponent />, document.querySelector(".myelement"));

You can take width variable like let width = '100px' and then apply this variable to your code like this. here width you can pass as a prop which could be any value
let width = '100px';
<div className="white-box v-align ht-100" style={{ width: width, marginRight: '10px' }}>
<div className="flex-one"></div>
<div className="wd-80">
<div className="fs-xl fw-bold" style={{ color: '#142654' }}>{pct}%</div>
<div className="small-text">{text}</div>
</div>
</div>

Related

React - Modal expands div in footer div not on main screen

New to coding, trying to get a modal to work. It is not opening the way I expected it to.
The component is currently loaded within the footer div of my site. And when the button is toggled it simply hides or shows a div within the footer. I want it to appear in the centre of the webpage as a modal.
import React, {useState} from 'react';
import './policy.css'
export default function Policy() {
const [modal, setModal] = useState(false);
const toggleModal = () => {
setModal(!modal);
};
if(modal) {
document.body.classList.add('active-modal')
} else {
document.body.classList.remove('active-modal')
}
return (
<>
<div>
<button onClick={toggleModal} className='btn-modal'>
<p>Privacy Policy</p>
</button>
</div>
{modal && (
<div className="modal">
<div onClick={toggleModal} className="overlay"></div>
<div className="modal-content">
<h2>Privacy Policy</h2>
<p>This is the privacy policy</p>
<button className='close-modal' onClick={toggleModal}>Close</button>
</div>
</div>
)}
</>
);
}
The simplest way to achieve a modal effect is to use some CSS.
You could try a very crude style like (from MUI Modal docs):
const style = {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: "lightgrey",
border: "2px solid #000",
boxShadow: 24,
padding: 4,
};
Then apply it to your modal:
<div className="modal" style={style}>

How to set up an image in an div using backgroundImage?

I have an div in which I have to display a photo using backgroundImage.
I have an object in which an as URL path for the image which I later on return from the obect.
I made the following code :
import React from 'react'
import './user.css';
const User = ({name,img,position,names}) => {
return ( <div className = 'card'>
<div id='image' style={{
backgroundImage: `url({${img}})`
}}></div>
<p className = 'card_name' id = 'based'>{name}</p>
<p className = 'card_position'>{position}</p>
<p>{names + ' '}</p>
</div>
);
}
export default User;
When I try to run the page I dont have any errors but my image does not appear on the page. What my seem to be the problem?
You have extra parentheses on the value you are passing to the URL, Try this:
You also need to add a height and width to the div
style={{
height: "200px",
width: "100%",
backgroundImage: `url(${img})`,
}}

How to display default and props values in react js?

I want to display default value="playlist" and when the user click it replace with default value, show the props values.
Right now its show the props value when i click the menu but i want to show the playlist name there and then its switch the value/name with props when user click menu
var defaultValue="playlist";
return (
<div className="mainContent">
<div className="tableHeaderBody">
<div className="TableText">{props.val}</div> <div className="ClossIcon"><FaCircle style={{ color: "#FC0000", width: "10px", height: "10px", alignItems: "right" }} /></div>
</div>
</div>
You can define the prop value as state, and setState when you call the onClick function.
const [playlist, setPlaylist] = useState("playlist");
return (
<div className="mainContent">
<div className="tableHeaderBody">
<div className="TableText">{playlist}</div> <div className="ClossIcon"><FaCircle style={{ color: "#FC0000", width: "10px", height: "10px", alignItems: "right" }} /></div>
</div>
</div>
And from wherever you call onCLick, define like this
OnClick={()=>setPlaylist(props.val)}

Linking to a different page using react-day-picker and react router v4

I'm trying to utilize this example in order to create a calendar that lists out the events in the current month, I have this part working, but what I have yet to figure out is how to make it so that the user can click the event name and it would take them to that event page.
So per that example, if they click on one of the birthdays, it would take them to an events page where they could see more about that birthday.
Currently, my events page is being rendered using this function:
renderEvents() {
const {events} = this.state
this.state.events = {};
let eventItems = this.state.eventGet.map(event => {
console.log(event.id)
if(typeof(events[moment(event.date).date()]) !== "undefined") {
events[moment(event.date).date()].push(event.name)
} else {
events[moment(event.date).date()] = [event.name]
}
});
function renderDay(day) {
const date = day.getDate();
const dateStyle = {
position: 'absolute',
color: 'lightgray',
bottom: 0,
right: 0,
fontSize: 20,
};
const containerStyle = {
margin:'2px',
border: '1px solid #3a87ad',
borderRadius: '3px',
position: 'relative',
display: 'block',
cursor: 'pointer'
};
const textStyle = {
fontSize: '0.8em',
textAlign: 'left',
margin: '1.5px',
}
const cellStyle = {
height: 150,
width: 160,
position: 'relative',
};
return (
<div style={cellStyle}>
<div style={dateStyle}>{date}</div>
{events[date] &&
events[date].map((name, i) => (
<div onClick={() => this.props.history.push('/organizations/' + this.props.match.params.orgID + '/events' + i)} key={i} style={containerStyle}>
<div style={textStyle}> {name} </div>
</div>
))}
</div>
);
}
return (
<div>
<Grid component="section" className="section--center" shadow={0} noSpacing>
<Cell col={12}>
<FABButton style={{margin: '10px', float: "right"}} colored ripple onClick={() => this.props.history.push('/organizations/' + this.props.match.params.orgID + '/events')}>
<Icon name="add" />
</FABButton>
</Cell>
<DayPicker
canChangeMonth={true}
className="Birthdays"
renderDay={renderDay}
/>
</Grid>
</div>
);
}
The current problem is within the sub-function, renderDay which is called by the DayPicker component that gets the events associated with the day. When I try to push to the history property, it errors out and says that I cannot read property 'history' from undefined, which makes sense because we did not pass the history property to that function.
Can someone help me in figuring out how to modify that sub-function so that the onClick event on the div will take a user to that events page?
and says that I cannot read property 'history' from undefined
Make sure your renderDay function is bound to the correct this:
<DayPicker
canChangeMonth
className="Birthdays"
renderDay={renderDay.bind(this)}
/>

can this.props be used to style the div tag?

I would want to use the this.props data in the div tag. i have the color in the data which i would want to set dynamically . Would it be possible to use this.props in the div tag?
var cont = {
height: "90px",
width: "20%",
background: "LightBlue",
display: "inline-block",
padding: "5px",
margin: "5px"
};
var Comment = React.createClass({
render: function () {
return (
<div style={cont}>
<span>
{this.props.author}
{this.props.col}
</span>
</div>
);
}
});
Look:
var Comment = React.createClass({
render: function() {
return (
<div style={{backgroundColor: this.props.col}}>
<span>
{this.props.author}
{this.props.col}
</span>
</div>
);
}
});
this.props.color here is a prop of Comment component and not of the div. You can use this prop wherever you want in this component.
As #MayankShukla said, for updating field in style object you can use Object.assign.
Try this:
<div style={{backgroundColor: this.props.col}}>
Offical React style documentation

Resources