Get Width Of An Element Inside A Dumb React Component - javascript

So I want to know the width of an element in react dumb component.
import React from 'react';
import moment from 'moment';
const Message = ({ ...props }) => (
<article>
<section> <!-- This is the element I want to find width of -->
<h2>{name}</h2>
<p>{description}</p>
</section>
<p>{moment(created_at).format("h:mm a")}</p>
</article>
);
export default Message;
I want to find the width of the section element, so that I can do some UI changes based on that width. The thing to note here is that this Message component is being mapped in an array. And for every Message component that get's rendered I want to find the width of the section element in each of that component.
I did some research and I found an implementation in a smart component which was like this.
class MyComponent extends Component {
componentDidMount () {
console.log(this.myInput.offsetWidth)
}
render () {
<div ref={input => {this.myInput = input}}>some elem</div>
}
}
Can I do similar like this but without using this or without using state, just plain old vanilla JavaScript.
Any kind of help or direction would be highly appreciated, Cheers :)

Related

How to make a container width bigger in React

I want to create an event for my button that is in in my AsideMenu component that take the current width and if it's equal to 5vw than it will make it to 10vw else it will put it at 5vw and it must overlap the div named home. This is the code:
Thank you
I know how to do it with it vanilla javascript but not in react
import React from 'react'
import AsideMenu from '../components/AsideMenu'
import './Home.css'
const Home = (props) => {
return (
<div className='assemble'>
<div >
<AsideMenu />
</div>
<div className='home'>
<h1>Home</h1>
</div>
</div>
)
}
export default Home```
You can use a useRef hook and get the current width. This video will explain it better for you. In case you get stuck, feel free to reach out. After using the useRef, you can then use a ternery statement in the return statement to actualize the code.

How to nest the class of parent component in child component?

I'm in a learning phase of react and I've been trying to nest style of parent in component in child component via class in react.js. How to do it?
What I've tried until now:
function Card(props) {
const classes = 'card' + props.className;
return (
<div className={classes}>
{props.children}
</div>
)
}
export default Card
I applied style on class 'card' in a CSS file.
Parent component JS code:
import Card from './UI/Card';
function ExpenseItem(props){
return (
<Card className="expense-item">
<ExpenseDate date={props.date} />
<div className="expense-item__description">
<h2>{props.title}</h2>
<div className="expense-item__price">{`₹ ${props.amount}`}</div>
</div>
</Card>
)
}
Now, there are various classes in parent component that are styled accordingly. And I'd like to nest those classes in child component for those style to work.
You can see in the code the way I tried to nest the classes, but it isn't working.
const classes = 'card' + props.className;
What am I doing wrong? And how should I correct it?
You missed a space after the card class name, otherwise i don't see any other issues in your code. Try below, hope it works
const classes = 'card ' + props.className;
Just one note, this will make your components dependent on each other. One of best things about React is that it allows you to have separation of concerns. So Card component is doing Card component staff, displaying some information and needs not be dependent on a parent in this case ExpenseItem.
One way to do it is to use styled-components.

How can I add a react Component To the DOM with jquery?

This is prob a super easy question but, I want to add components to a grid with react and jquery.
gridGame is a black 100px by 100px square and I want to add items into it. Im using rows (a variable) witch is a number from 1-9 to and sumbing it in to the gridGame-${rows} as seen here,so it can auto update the correct row to join. value should be: gridGame-${row} (what ever number row is from 1-9) and then I want to add a component inside gridGame called <Test /.> (witch is declared up-top in unseen parts of the code).
The function below has jquery that I thought would work in this situation:
function = (rows) => {
console.log(`joining ${rows}`)
let value= $(`#gridGame-${rows}`);
value.append("<Test />");
value.css("background-color", 'brown');
$(".create-coinflip-box").css("display", "none");
}
The css background change works but the value.append does not display the react component.
Here is the React Component inside the <Test /.>:
import React from 'react';
import StatusIcon from './img/image.png';
import Player1Icon from './img/image.png'
class newGame extends React.Component {
render() {
return(
<div>
HELLO
</div>
);
}
}
export default newGame;
I honestly have 0 idea on how this doesn't work.
Thanks for the help :)
This answer was from David in the comments. The problem for me was I was trying to render a component through a button and not the actual render its self.
The solution is to instead make the button change the state witch Updates the React DOM. Then just have a if statement that checks the state then display the component.
His comment explains much better and fixed the problem for me.

How to force Antd to append element as child element of div React renders to instead of to HTML body?

Edit:
I figured it out & posted answer below.
Original Question
I am trying to create a completely compartmentalized web application within a shadow-dom and I've been using Antd components and ran into the issue where Antd is appending drop-down options into the body tag instead of as a child of the element that React is rendering into.
To isolate this issue I've removed everything outside of just React.render & a single Antd element which still does the same thing.
I then used a different component, "react-date-picker", which works how I had hoped Antd did, where the component renders as a child of the div specified for react.
Unfortunately, Antd rendering to the body of the HTML instead of as a child makes using shadow-root pointless.
Essentially my question is:
Is this Antd's normal functionality? If not then what might I be screwing up to have this happen? If so then is there a built-in Antd option that I'm missing that will render Antd options as child elements? If that option doesn't exist within their libraries, is there a way for me to force Antd to render as a child of my shadow-root node?
Here is what I'm using to render the Antd DatePicker component:
import ReactDOM from 'react-dom';
import React from 'react';
import DatePicker from 'antd/lib/date-picker';
ReactDOM.render(<DatePicker/>, document.getElementById('entry-fields'));
Before clicking on the Antd date picker:
After clicking on it, drop down options are appended to <body> and not <div id="entry-fields>:
Here is what I'm using to render the react-date-picker component to demonstrate the functionality I expected / need:
import ReactDOM from 'react-dom';
import React from 'react';
import DatePicker from "react-datepicker";
class Example extends React.Component {
state = {
startDate: new Date()
};
handleChange = (date: any) => {
this.setState({
startDate: date
});
};
render() {
return (
<DatePicker
selected={this.state.startDate}
onChange={this.handleChange}
/>
);
}
}
ReactDOM.render(<Example/>, document.getElementById('entry-fields'));
Before clicking on the react-date-picker date picker:
After clicking on the react-date-picker date picker (the drop down options are appended as children of the element react is rendered onto):
Basically I expected Antd to render its options encapsulated within the React rendered into <div></div> but it is instead appending elements on the <body></body>.
I'm relatively inexperienced in the web-dev domain and have resorted to asking a question here after way too much time trying to find the answer on my own. I am getting extremely frustrated in web-dev in general where any question seems to yield hundreds of irrelevant medium blog posts that are not useful in any capacity... assuming that it's not just me not knowing what to search for yet to find the answers I need which could very well be the case.
Really appreciate any help in advance.
Not sure how I managed to miss this but Antd has a parameter called "getCalendarContainer" which if left blank will render options into the body of the document but if supplied with the correct parameters will render the child elements into the container of your choosing.
Going off this example: https://react-component.github.io/calendar/examples/getCalendarContainer.html
I got it working by adding this function to my component:
getCalendarContainer()
{
return this.d || document.getElementById('calendarContainer');
}
and adding this to the component in JSX:
<div id="calendarContainer" ref={n => (this.d = n as HTMLDivElement)} >
<DatePicker onChange={EntryFields.onDateChange} getCalendarContainer={this.getCalendarContainer}/>
</div>
and initializing the div tag to reference it in the component's constructor like this:
private d: HTMLDivElement;
constructor(props: any)
{
super(props);
this.d = document.createElement("div");
...
It's also worth noting that the above will not work immediately when using shadow-DOM since you need to access the node that the shadow-DOM is a child to and then use getElementById().
Something along these lines (but probably better written I hope lol)
getContainer() {
let elem = null;
let shadowContainer = document.getElementById('entryFieldsShadow') as HTMLInputElement;
if (shadowContainer != null) {
let shadowDom = shadowContainer.firstElementChild;
if (shadowDom != null) {
let shadowRoot = shadowDom.shadowRoot;
if (shadowRoot != null) {
elem = shadowRoot.getElementById("entryFieldsContainer")
}
}
}
return elem || this.d;
}
where the JSX with react-shadow's shadow root is included looks like this:
return (
<div id="entryFieldsShadow">
<root.div>
<div>
<div id="entryFieldsContainer"/>
<style type="text/css"> #import "static/1.css"; </style>
<Layout>
<Content>
{this.RowCols()}
</Content>
</Layout>
</div>
</root.div>
</div>
)
This solve my problems
<DatePicker
{...}
getCalendarContainer={triggerNode => triggerNode.parentNode}
/>

react-split-pane cannot resize

I just installed react-split-pane in my application, but it does not seem to work.
I'm using react-split-pane version 0.1.68 but I tested it with 0.1.66 and 0.1.64 as well.
This is my component:
import React, { Component } from 'react';
import SplitPane from 'react-split-pane';
class Edit extends Component {
render() {
return (
<SplitPane split="vertical">
<div style={{backgroundColor: 'red'}}>LEFT</div>
<div style={{backgroundColor: 'blue'}}>RIGHT</div>
</SplitPane>
);
}
}
export default Edit;
I end up with a component that looks like I how styled it, but dragging between the elements to resize the width of the elements does not work.
What am I missing here?
Ps this issue might be related to it, but I tried previous versions and they don't seem to work either.
I had a similar problem. The reason why divider doesn't work is: missing CSS
Add CSS from tutorial: https://github.com/tomkp/react-split-pane#example-styling
to your react component. For example:
import './edit.css';
Your dragging element will work.

Categories

Resources