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.
I'm trying to make a simple app that counts the number of times the button has been clicked. I read this is a good first question in JS interviews.
"Ask the candidate to build a click counter using any popular framework (React preferred in 2020). This ridiculously simple app has one job: keep track of how many times the user has clicked the button during the current session. No storage. No network I/O. Just count clicks. It is intentionally ridiculously simple"
My first instinct would be to use hooks, but the question wants the programmer to do it without using storage which I believe includes using state.
import React from 'react';
import './App.css';
function App() {
let count=0;
const add=()=>{
debugger;
count++;
}
return (
<header className="App-header">
<button onClick={()=>add()}>click me</button>
{count}
</header>
);
}
export default App;
Here is what I tried. Using debugger I can see count does go up but the changes aren't showing on the page. Any advice would be appreciated.
React is a JS library so we can use pure js:
function App() {
return (
<div className="App">
<h1 id="c">0</h1>
<button
onClick={() => {
let c = document.getElementById("c");
c.innerHTML = parseInt(c.textContent)+1;
}}
>
+
</button>
</div>
);
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
The reason your code doesn't produce the expected result is that React doesn't update the dom unless it sees that an update is necessary, i.e., because the state of the component changed.
So, in your case, the component only gets rendered once, when the value of count is 0. If you want to React to re-render the component and show you the new value, you'll have to trigger that with a state change. Alternatively you can follow cybercoder's solution, which actually opts out of React by supplying its own innerHTML.
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.
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 :)
What would be the best way to implement RTL support in React apps? Is there a way to override default <p> and <span> tags (components) to add RTL support so that I don't have to rewrite components I already wrote to have RTL support? (for example, to have some global variable window.RTL, so when set to true to have all <p> and <span> tags flip text direction to RTL). I could probably change the build system, or make a babel plugin, that will replace all React.createElement("p" ...) with my own implementation of a p tag, but is there a better solution?
Thanks.
A more optimal way is to use CSS / HTML abilities for that:
direction CSS property
Unicode symbols /
Attach .rtl / .ltr classes to body and use them to change order
In that cases order of your elements in HTML are the same for RTL and LTR. The difference in applied CSS rules.
If you really need the order of elements in React, you can create own component that reverses the list of children if RTL:
const Dir = React.createClass({
render: function() {
let children = (this.props.direction == 'rtl' && this.props.children && this.props.children.reverse) ? this.props.children.reverse() : null;
return <div>
{ children }
</div>;
}
});
// And use as:
// directionVariable = 'rtl'|'ltr'
<Dir direction={ directionVariable }>
<a>First</a>
<a>Second</a>
<a>Third</a>
</Dir>
Simple and easy, Just set dir attribute of <html> in index.js as follow:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
//HERE ->
document.getElementsByTagName('html')[0].setAttribute("dir", "rtl");
//Or you can do it where ever you want, base on user selected language, or something else
serviceWorker.unregister();
UPDATE: If your application is RTL at all, just add dir="rtl" in <html> tag, but if user can chose different languages that may be RTL or LTR you can do it like above example, and handle other things with CSS...
Just check User chosen language is RTL and document.getElementsByTagName('html')[0].setAttribute("dir", "rtl"); let CSS handle appearance stuff.
here's your solution:
first of all create an array of rtl language locales, like this:
const rtlLanguages = ["ar"]
here's how you can update your page direction based on your current language:
function setPageDirection(language) {
const dir = rtlLanguages.includes(language) ? "rtl" : "ltr"
document.documentElement.dir = dir
}
now when you set your new language, update the page direction using the function above, like this:
setPageDirection("en") // ltr
setPageDirection("ar") // rtl
NOTE: to automatically update the page direction during first render try storing your current language locale (for example: "en") in localStorage whenever you update your language, and then try using useEffect (or componentDidMount), and use localStorage.getItem to get your language and just call the setPageDirection function and provide the language
There is a special HTML tag to use RTL direction:
bdo {
unicode-bidi: bidi-override;
}
<bdo dir="rtl">
This text will go right-to-left.
</bdo>
https://www.w3schools.com/tags/tag_bdo.asp
if you use react-i18next
import React from 'react';
import { useTranslation } from 'react-i18next';
import './App.css';
function App() {
const { t, i18n } = useTranslation();
document.body.dir = i18n.dir();
return (
<div className="App">
{t('welcome')}
</div>
);
}
export default App;
Go to main.tsx or main.js depending on your project and wrap <App /> tag with a <div dir="rtl"></div> like this
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<div dir="rtl">
<App />
</div>
</React.StrictMode>
)
I'm using react-i18next to change the position from left to right when the Arabic language is chosen. I did the flowing, and it worked for me.
first i went to to the index.html and wrote this inside of body tag:
<body dir="ltr">
which will allow the page to left to write when the direction is chosen.
lastly i add this line in my App.js which is my main code:
document.body.dir = i18n.dir(); //this will change the direction of the dir in the index.html.