Styling a child element in a third-party component - styled-components

I'm using a 3rd party component named "Dialog" with the render method below. As you can see - the component has more than one className. I'd like to create a styled-component called StyledDialog which contains a prop that lets me override the width associated with the div that has the "SURFACE" className. Can this be done with Styled-Components - or do I need to bring the source code into my app and handle that manually.
render() {
const { className, children, onClose, open, ...otherProps } = this.props;
const ariaHiddenProp = open ? {} : { 'aria-hidden': true };
return (
<aside
className={classnames(
ROOT,
{
[ANIMATING]: this.state.animating,
[OPEN]: open,
},
className
)}
onClick={(e) => {
if (onClose) onClose(e);
}}
onTransitionEnd={() => {
this.setState({ animating: false });
}}
{...ariaHiddenProp}
>
<div
className={SURFACE}
onClick={(e) => {
e.stopPropagation();
}}
{...otherProps}
>
{children}
</div>
<div className={BACKDROP} />
</aside>
);
}

Based on your explanation, i think you should wrap this 3rd party component with styled method and apply your styles by referencing the corresponding classnames of that component from the wrapped styled component.
For instance, If the name of existing component is Hello, you can apply styling from a styled-component on any of its DOM children like this:
const StyledHello = styled(Hello)`
.${classes.SURFACE} {
width: 10rem;
border: 2px solid green;
}
`;
Working Demo

Related

Load specific DIV with a react component without reloading the whole page

I have a menu where every menu item is a button and I want to load a specific reactjs component into a specific div without reloading the whole page.
This is the current code, clearly is bad but I don't know where to start fixing it...
...
<Button onClick={this.loadTarget}>
{menuItem.name}
</Button>
...
loadTarget(event) {
document.getElementById("datapanel").innerHTML="abc<TranslationsList />";
}
When I click a menu Item I want to load my div with the value "abc<TranslationsList />". "abc" is displayed but the custom component "TranslationsList" is not and I guess this is normal as the TranslationsList tag is not a HTML tag. But how could I load my component?
I could use links instead of buttons but in this case the question is how could I update the div content with a specific link?
It's hard if you've programmed plain JS before, but you have to forget the "good old JS pattern" in React. I also had a hard time getting used to not using standard JS elements (target, innerHTML, etc.) to solve such a problem.
So the solution in React is to use the framework and your page reload problem will be solved immediately. useState for the state of the component and handlers for the click. My main code looks like this. You can find a working application at Codesandbox.
export default function App() {
const [showComponent, setShowComponent] = useState(false);
const handleButtonClick = (e) => {
setShowComponent(!showComponent);
};
return (
<div className="App">
<h1>
Load specific DIV with a react component without reloading the whole
page
</h1>
<a href="https://stackoverflow.com/questions/74654088/load-specific-div-with-a-react-component-without-reloading-the-whole-page">
Link to Stackoverflow
</a>
<div style={{ marginTop: "20px" }}>
<button onClick={handleButtonClick}>Magic</button>
</div>
{showComponent ? (
<div style={{ marginTop: "20px" }}>
This is the place of your component!
</div>
) : (
""
)}
</div>
);
}
In the first place I wpuld not use vanilla JS syntax on a react app if it is not necessary. i.e: document.getElementById("datapanel").innerHTML="abc<TranslationsList />".
If you are using React you should be managing the State in the component of the DIV, giving the order to make an element appear once the button is clicked.
A simple example can be this:
CodeSandbox
import { useState } from "react";
export default function App() {
const [divState, setDivState] = useState(null);
const divElement = () => <div>I am the element that should appear</div>;
const handleDiv = () => {
setDivState(divElement);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={handleDiv}>Show DIV</button>
<div>{divState}</div>
</div>
);
}
I agree with the answers given above. Since you are already using React, you should take advantage of its features/functionalities. No need to reinvent the wheel.
However, if you are still interested in how to make your current implementation work. You may use renderToString(), which can be imported from ReactDOMServer. Please refer to the following code snippet as an example.
import { renderToString } from 'react-dom/server'
const TranslationsList = () => {
return <div>TranslationsList Content</div>
}
export default function App() {
const loadTarget = () => {
document.getElementById("datapanel").innerHTML=`abc${renderToString(<TranslationsList />)}`;
}
return (
<div>
<button onClick={loadTarget}>Insert Component</button>
<div id="datapanel">Data Panel Holder</div>
</div>
);
}

How to change the text and path of a navigation button?

I have a navbar component, which has a button that transforming me to path (React-Router) "/NEXUM", But, When I'm transformed to NEXUM, i want to change the text of the navbar and the navigation path, so when I click it, it will bring me to a different path, called "/".
const NavBar = () => {
const navigate = useNavigate()
const homeToNavigate = () => {
navigate('/')
}
const Navigation = () => {
navigate('/nexum')
}
return (
<Box sx={{ flexGrow: 1 }}>
<AppBar id="bar">
<Toolbar>
<img onClick={homeToNavigate} className="logo" src={logo}></img>
<Button onClick={Navigation} id='nexumNavigation'> להכנסת קובץ אקסל ישיר </Button>
</Toolbar>
</AppBar>
</Box>
)
}
export default NavBar
This is The nav bar component, The "navBar" component is used in both "HomePage" Component that I'm using and "SpagetiComponent", So as I said, I need the purpose of the button to change, I tried doing it with props, but I was unsuccessful, if you have an idea, please let me know.
let location = useLocation();
<Button onClick={location.pathName==="/NEXUM"?homeToNavigate:Navigation} id='nexumNavigation'>{location.pathName==="/NEXUM"?"go home":"go NEXUM"} </Button>

React - trying to save fetched data in a variable but the variable returns empty

I fetched json data with async await and i wanted to save the fetched data in a variable in order to be able to use it with a map in my component,
the data comes in properly inside the function - i checked with an alert , and also in the variable inside the function it does display all the data , but somehow the variable outside the function returns empty .
here is some code:
both alerts in the following code return the right data.
export let fetchPosts = [];
export async function FetchPosts() {
await axios.get('https://jsonplaceholder.typicode.com/posts').then(
res => {
alert(JSON.stringify(res.data))
fetchPosts = JSON.stringify(res.data);
alert(fetchPosts)
}
).catch(err => {
alert('err');
})
}
import { fetchPosts } from '../services/post';
import { FetchPosts } from '../services/post';
export default function Posts() {
function clickme() {
FetchPosts()
}
return (<>
<button onClick={clickme}>Click me</button>
{fetchPosts.map((post, index) => (
<div key={post.id} className="card" style={{ 'width': '16rem', 'display': 'inline-block', 'margin': '5px' }}>
<div className="card-body">
<h6 className="title">{post.title}</h6>
<p className="card-text">{post.body}</p>
</div>
</div>
))}
</>)
}
State is the issue
React doesn't automatically reload on your singleton fetchPosts.
Instead, try...
export function FetchPosts() {
return axios.get('https://jsonplaceholder.typicode.com/posts');
}
then
import { useState } from 'react';
import { FetchPosts } from '../services/post';
export default function Posts() {
const [posts, setPosts] = useState([]);
function clickme() {
FetchPosts().then(res => {
setPosts(res.data);
});
}
return (<>
<button onClick={clickme}>Click me</button>
{posts.map((post, index) => (
<div key={post.id} className="card" style={{ width: '16rem', display: 'inline-block', margin: '5px' }}>
<div className="card-body">
<h6 className="title">{post.title}</h6>
<p className="card-text">{post.body}</p>
</div>
</div>
))}
</>)
}
https://codesandbox.io/s/jolly-almeida-q4331?fontsize=14&hidenavigation=1&theme=dark
If you want global state, that's another topic you should dive into entirely but you can do it with a singleton, you just need to incorporate it with hooks and an event emitter. I have a bit of a hacked version of this here https://codesandbox.io/s/react-typescript-playground-forked-h8rpu but you should probably stick to redux or mobx or AppContext which is more of a popular pattern.

Scroll to particular component in Preact

i am working on preact app and i have different components imported in a single page, i want to click on button in header and scroll to particular component.
this is my parent component
<div class={style.root}>
<Header />
<Landing />
<HowItWorks />
<BrowserCatalogue />
<ContactUs />
<Footer />
</div>
and in my header i have 3 buttons
<div class={styles.headerItems}>
<span style={styles.pointer}>Working</span>
<span style={styles.pointer}>Catalogue</span>
<span style={styles.pointer}>Contact</span>
</div>
</div>
like when i click on working my page should scroll to HowItWorks component.any help?
Let me help you friend. You should introduce refs in your parent component.
We will wrap each section in a div and give it a ref prop.
Here is sandbox for your reference: https://codesandbox.io/s/navbar-click-scroll-into-section-us8y7
Parent Component
import React from "react";
import ReactDOM from "react-dom";
import Header from "./Header";
import HowItWorks from "./HowItWorks";
import BrowserCatalogue from "./BrowserCatalogue";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
selected: null
};
}
//refs
howItWorks = React.createRef();
browserCatalogue = React.createRef();
changeSelection = index => {
this.setState({
selected: index
});
};
componentDidUpdate() {
this.scrollToSection(this.state.selected);
}
scrollToSection = index => {
let refs = [this.howItWorks, this.browserCatalogue];
if (refs[index].current) {
refs[index].current.scrollIntoView({
behavior: "smooth",
block: "nearest"
});
}
};
render() {
return (
<div className="App">
<div>
<Header changeSelection={this.changeSelection} />
</div>
<div ref={this.howItWorks}>
<HowItWorks />
</div>
<div ref={this.browserCatalogue}>
<BrowserCatalogue />
</div>
</div>
);
}
}
Header
const Header = (props) => {
const { changeSelection } = props;
return (
<div style={{ background: "green" }}>
<span onClick={() => changeSelection(0)}>Working</span>{" "}
<span onClick={() => changeSelection(1)}>Catalogue</span>{" "}
<span>Contact</span>
</div>
);
}
Workflow:
Each component gets a ref, and we keep that in memory for when we
need to scroll.
Header, we defined a handler in parent called changeSelection()
and we pass it as prop. It takes an index and we use that index to
update the parent state.
Each link, "Working", "Catalogue", etc, will correspond to an index
that matches with a ref in our parent, so setting up an onClick() handler for each span will allow us to pass in that index to changeSelection()
parent state is updated, triggers componentDidUpdate(), in there
we run scrollToSection() which you guessed it takes in an index (stored in our state as "selected"). Create an array of our refs, and simply use the matching index to locate that ref and scroll to that component.

How to implement dynamic flex value with Angular Material

I'm trying to build a div with uncertain number of child divs, I want the child div have flex="100" when there is only one of them, which takes the entire row. If there are more than one child divs (even if there are three or four child elements), they should all have exactly flex="50", which will take half of the row.
Any idea how could I do that?
Thanks in advance.
Another way is <div flex="{{::flexSize}}"></div> and in controller define and modify flexSize e.g $scope.flexSize = 50;
Thanks for the help from #William S, I shouldn't work with flex box for a static size layout.
So I work with ng-class to solve my problem.
HTML:
<div flex layout-fill layout="column" layout-wrap>
<div ng-repeat="function in functions" ng-class="test" class="card-container">
<md-card>
contents
</md-card>
</div>
</div>
My CSS is like the following:
.test1 {
width: 100%;
}
.test2 {
width: 50%;
}
The initial value of $scope.test is 'test1',by changing the value from 'test1' to 'test2', the width of children divs will be set to 50%.
Defining "flex" inside an element will always try to take up the most amount of space that the parent allows, without supplying any parameters to flex. This needs to be accompanied by layout="row/column", so flex expands in the right direction.
Is this what you're looking for?
http://codepen.io/qvazzler/pen/LVJZpR
Note that eventually, the items will start growing outside the parent size. You can solve this in several ways, but I believe this is outside the scope of the question.
HTML
<div ng-app="MyApp" ng-controller="AppCtrl as ctrl">
<h2>Static height list with Flex</h2>
<md-button class="thebutton" ng-click="addItem()">Add Item</md-button>
<div class="page" layout="row">
<md-list layout-fill layout="column">
<md-list-item flex layout="column" class="listitem" ng-repeat="item in items" ng-click="logme('Unrelated action')">
<md-item-content layout="column" md-ink-ripple flex>
<div class="inset">
{{item.title}}
</div>
</md-item-content>
</md-list-item>
</md-list>
</div>
</div>
CSS
.page {
height: 300px; /* Or whatever */
}
.thebutton {
background-color: gray;
}
.listitem {
/*height: 100px;*/
flex;
background-color: pink;
}
JS
angular.module('MyApp', ['ngMaterial'])
.controller('AppCtrl', function($scope) {
$scope.items = [{
title: 'Item One',
active: true
} ];
$scope.addItem = function() {
newitem = {
title: 'Another item',
active: false
};
$scope.items.push(newitem);
}
$scope.toggle = function(item) {
item.active = !item.active;
console.log("bool toggled");
}
$scope.logme = function(text) {
alert(text);
console.log(text);
}
});
Use below :
scope.flexSize = countryService.market === 'FR'? 40: 50;
<div flex="{{::flexSize}}">

Resources